Python:Multipart html电子邮件与嵌入式图像和附件一起发送

时间:2016-11-01 14:51:41

标签: python html email jinja2 mime

我查了很多关于它的帖子,但仍无法找到解决方案。 我能够发送包含嵌入图片的电子邮件,但电子邮件还包含这些图片作为附件,我只需要嵌入图片。我尝试过很多变种,有'相关'类型,'混合'。还有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()

jinja模板:

<html>
<body>
{% for image in pictures %}
<img src="cid:{{image}}">
{% endfor %}
</body>
</html>

1 个答案:

答案 0 :(得分:1)

首先附加HTML或指定&#34; start&#34; multipart / related内容类型的参数。

引用RFC2387

  

如果给定,则start参数是化合物的content-ID      对象&#34; root&#34;。如果不存在&#34; root&#34;是第一个身体部位      Multipart / Related实体。 &#34; root&#34;是元素      申请流程首先。

因此,在您的示例中,您可以进行这些更改以标记根元素:

mail = MIMEMultipart("related", start="<HTML>", type="text/html") 
...
msgHtml.add_header('Content-ID', '<HTML>')

至少在Google Mail中,要么首先放置HTML,要么添加&#34; start&#34;参数允许图像以内联方式显示。

完整示例:

from jinja2 import Template
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from glob import glob
from getpass import getpass
import smtplib

me = 'example@gmail.com'
you= 'example@gmail.com'
auth = ('example@gmail.com', getpass())
mx=  ('smtp.gmail.com', 465)

list_of_images = glob('*.jpg')

mail = MIMEMultipart("related")
#Jinja2 for html template
main = Template('''
    <html><body>
    {% for image in pictures %}<img src="cid:{{image}}">{% endfor %}
    </body></html>''')
html = main.render(pictures=list_of_images)
msgHtml = MIMEText(html, 'html')
mail.attach(msgHtml)

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)

mail['Subject'] = "TEST"
mail['From'] = me
mail['To'] = you

s = smtplib.SMTP_SSL(*mx)
s.login(*auth)
s.sendmail(me, you, mail.as_string())
s.quit()