【问题标题】:Django EmailMultiAlternatives with Embadded Image in HTML带有 HTML 中嵌入图像的 Django EmailMultiAlternatives
【发布时间】:2011-09-19 00:26:25
【问题描述】:

我正在尝试发送带有 HTML 和嵌入图像的电子邮件。电子邮件发送工作正常,并且它还在电子邮件中附加了图像,但它没有以 HTML(内联)显示图像。我在视图中使用了 Content:ID 并在模板中使用了 cid ,但没有成功:(。我探索了很多表格并应用了解决方案,但徒劳无功,请帮助!这是我的代码:

html_content = render_to_string('newsletters/newsletter_template.html', vars)
text_content = strip_tags(html_content) 

to = 'myemail@gmail.com'


msg = EmailMultiAlternatives(self.subject, text_content, settings.STAFF_FROM_EMAIL, [to])
msg.attach_alternative(html_content, "text/html")

image_file = open('../media/images/banner_admin.gif', 'rb')
msg_image = MIMEImage(image_file.read())
image_file.close()

msg_image.add_header('Content-ID', '<image1>')
msg.attach(msg_image)

msg.send()

模板文件:

<div style="border:2px solid #CCCCCC; width:900px; font-size:10px; padding:5px;">
    <div style="margin-bottom: 10px;"><img src="cid:image1" /></div>
    <div style="">{{body|linebreaks}}</div>
</div>

如果我在这里遗漏了什么,请告诉我...

【问题讨论】:

  • 嗨。你的代码对我有用。我收到了一封带有 GMail 的格式化电子邮件,它工作正常。

标签: python django email


【解决方案1】:

要在电子邮件正文中嵌入 PNG 文件,请尝试以下代码:

for f in ['img1.png', 'img2.png']:
    fp = open(os.path.join(os.path.dirname(__file__), f), 'rb')
    msg_img = MIMEImage(fp.read())
    fp.close()
    msg_img.add_header('Content-ID', '<{}>'.format(f))
    msg.attach(msg_img)

msg.send()

现在您可以在模板中使用&lt;img src="cid:img1.png"&gt;。结果应该是电子邮件客户端在&lt;img&gt;标签的位置显示嵌入在邮件中的图像,而不是作为附件。

【讨论】:

    猜你喜欢
    • 2012-04-22
    • 2010-12-08
    • 2011-04-16
    • 2012-07-29
    • 1970-01-01
    • 2015-07-07
    • 2015-12-30
    • 1970-01-01
    相关资源
    最近更新 更多