我在.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('
Hello
', _subtype='html')html_part.attach(body)
img = MIMEImage(img_data, 'png')
img.add_header('Content-Id', '') # 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()