python-3.x - 发送带有内嵌图像的电子邮件 Flask-Mail?

标签 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(
            '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') }} ">
任何引用或想法为什么这些不起作用?

最佳答案

您需要在附件中添加“Content-ID” header 值。

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">

关于python-3.x - 发送带有内嵌图像的电子邮件 Flask-Mail?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55271348/

相关文章:

python - 使用 pip install 安装 ssl 时遇到问题 : "SyntaxError: Missing parentheses in call to ' print'"

电子邮件混淆问题

请求之间的 Python Flask 持久对象

python - flask REST API 错误 : The view function did not return a valid response

javascript - 如何部署 Flask Web 应用程序但仍隐藏我的源代码?

mysql - 从 Raspberry pi 连接到笔记本电脑上的 MySQL

python - Python 3 中的 PDF 合并

python - 将字典中的列表转换为系列

vba - 通过宏向多个收件人发送自定义电子邮件

c# - 验证 TLS 电子邮件接收