Python 3.x 使用内嵌图像发送电子邮件?

Python 3.x 使用内嵌图像发送电子邮件?,python-3.x,email,flask,Python 3.x,Email,Flask,我有一个应用程序,它使用Flask和Flask-Mail。我试图发送一封电子邮件,它使用html文件作为带有内联图像的模板。一切正常,只是我看不到图像。我的代码是: msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body msg.attachments = [ Attachment(

我有一个应用程序,它使用
Flask
Flask-Mail
。我试图发送一封电子邮件,它使用html文件作为带有内联图像的模板。一切正常,只是我看不到图像。我的代码是:

    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    msg.attachments = [
        Attachment(
            'header.gif',
            'image/gif',
            open(join(mail_blueprint.static_folder, 'header.gif'), 'rb').read(),
            'inline'
        )
    ]
    mail.send(msg)
对于html文件,我尝试了几种引用方式,如:


是否有任何参考或想法说明这些方法不起作用?

您需要在附件中添加“内容ID”标题值

msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
msg.html = html_body
msg.attach('header.gif','image/gif',open(join(mail_blueprint.static_folder, 'header.gif'), 'rb').read(), 'inline', headers=[['Content-ID','<Myimage>'],])
mail.send(msg)
msg=Message(主题,发件人=发件人,收件人=收件人)
msg.body=text\u body
msg.html=html\u正文
msg.attach('header.gif','image/gif',open(加入(mail\u blueprint.static\u文件夹,'header.gif'),'rb').read(),'inline',headers=[['Content-ID',''],])
邮件发送(msg)
然后在模板中,您将通过Content-ID引用附件

<img src="cid:Myimage">


HTML模板(以及嵌入的
url\u for
)仅在.code>headers=[['Content-ID','''],]应该是dict时呈现-
headers={'Content-ID':''}
。我不知道为什么我的flask mail是0.9.1,并且代码没有固定,但您可以查看源代码以选择正确的方式。