在python中将图像嵌入电子邮件的正文中

时间:2016-03-03 20:44:41

标签: python email embed html-email smtplib

我在.png文件中有一张图片。我试图使用Python将此图像嵌入到电子邮件的正文中。我尝试了互联网上提供的各种选项,但他们提供了附加文件的解决方案,而不是嵌入电子邮件正文中。

这是我的代码段。我正在附加一个文件并尝试在电子邮件正文中添加图像(实际上是附加html文件而不是将图像添加到电子邮件正文)。在Python中是否可以在电子邮件正文中嵌入图像?

def send_report(send_from, send_to, subject, text, files=[], server="10.70.70.100",html=True):
#assert isinstance(send_to, list)
#assert isinstance(files, list)

msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject

if (html):
    part1 = MIMEText(text, 'html')
    msg.attach(part1)
else:
    msg.attach( MIMEText(text) )

for f in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(f,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

#Trying to embed image in email body
img_data = open('a.png', 'rb').read()
html_part = MIMEMultipart(_subtype='related')
body = MIMEText('<p>Hello <img src="cid:myimage" /></p>', _subtype='html')
html_part.attach(body)

img = MIMEImage(img_data, 'png')
img.add_header('Content-Id', '<myimage>')  # angle brackets are important
img.add_header("Content-Disposition", "inline", filename="myimage") 
html_part.attach(img)
msg.attach(html_part)

smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()

0 个答案:

没有答案