【发布时间】:2017-03-14 17:44:29
【问题描述】:
我查看了很多关于它的帖子,但仍然找不到解决方案。 我可以发送带有嵌入图片的电子邮件,但电子邮件还包含这些图片作为附件,我只需要嵌入图片。我尝试了很多变体,“相关”类型,“混合”。在 Python 程序中也有 html 代码(不在 Jinja2 模板中),但我无法让它工作。
list_of_images = get_graphs() #list with file names
# here if I put "related" - images are sent ONLY as attachments
mail = MIMEMultipart()
for filename in list_of_images:
fp = open(filename, 'rb')
msg_img = MIMEImage(fp.read())
fp.close()
msg_img.add_header('Content-ID', '<{}>'.format(filename))
msg_img.add_header('Content-Disposition', 'inline', filename=filename)
mail.attach(msg_img)
#Jinja2 for html template
env = Environment(loader=FileSystemLoader('.'))
main = env.get_template('images.tpl')
html = main.render(pictures=list_of_images)
msgHtml = MIMEText(html, 'html')
mail.attach(msgHtml)
mail['Subject'] = "TEST"
mail['From'] = "email@addr"
mail['To'] = "email@addr"
s = smtplib.SMTP("localhost")
s.sendmail(mail['From'], "email@addr", mail.as_string())
s.quit()
神社模板:
<html>
<body>
{% for image in pictures %}
<img src="cid:{{image}}">
{% endfor %}
</body>
</html>
【问题讨论】:
标签: python html email jinja2 mime