使用内嵌图像Flask-Mail发送电子邮件?

问题描述 投票:0回答:1

我有一个使用FlaskFlask-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文件,我尝试过几种方式引用它,例如:

<img src="cid:footer.gif"><img src="{{ url_for('mail.static', filename='header.gif') }} ">

任何参考或想法为什么这些不起作用?

python-3.x email flask
1个回答
0
投票

您需要在附件中添加“Content-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)

然后在您的模板中,您将通过Content-ID引用附件。

<img src="cid:Myimage">
© www.soinside.com 2019 - 2024. All rights reserved.