我正在尝试使用内嵌图像在Django中创建一个电子邮件.
msg = EmailMultiAlternatives(...)
image_file = open('file_path', 'rb')
img = MIMEImage(img_data)
image_file.close()
img.add_header('Content-ID', '<image1>')
img.add_header('Content-Disposition', 'inline')
msg.attach(img)
msg.send()
Run Code Online (Sandbox Code Playgroud)
在模板中我会像这样引用它:
<img src="cid:image1" />
Run Code Online (Sandbox Code Playgroud)
这在web浏览器,outlook,thunderbird中都很好用......除了OSX,iPad和iPhone上的苹果邮件客户端.图像显示两次.它们正确放置在内联,但它们也附在电子邮件的底部.我的问题是,如何摆脱底部的图像?或者我应该以不同方式处理电子邮件中的图像
参考文献:
http://djangosnippets.org/snippets/1507/
Django:如何发送带有嵌入式图像的HTML电子邮件,创建一个带有要使用python/django发送的图像
的MIME电子邮件模板
bra*_*ers 11
不同的电子邮件客户端选择以multipart/mixed不同方式呈现消息.
大多数客户选择按照添加到电子邮件中的顺序呈现内联的每个部分(在"多部分"消息中).但是,如果在text/html部件中引用图像,则大多数客户端稍后不会再次显示该图像,作为"内联所有部件"过程的一部分.
OSX和iOS上的Apple Mail是不同的,因为它们将multipart/mixed按照它们被包含的顺序显示消息中的每个部分,而不管HTML和图像之间的任何内部引用.这会导致您的图像在HTML中显示一次,并在消息结束时再次自动显示.
解决方案是将HTML和图像资源分组到一个related部分中.即:
from django.core.mail import EmailMultiAlternatives
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# HTML + image container
related = MIMEMultipart("related")
# Add the HTML
html = MIMEText('an image: <img src="cid:some_image"/>', "html")
related.attach(html)
# Add an image
with open("icon.png", "rb") as handle:
image = MIMEImage(handle.read())
image.add_header("Content-ID", "<some_image>")
image.add_header("Content-Disposition", "inline")
related.attach(image)
# top level container, defines plain text version
email = EmailMultiAlternatives(subject="demo", body="plain text body",
from_email="foo@example.com",
to=["bar@example.com"])
# add the HTML version
email.attach(related)
# Indicate that only one of the two types (text vs html) should be rendered
email.mixed_subtype = "alternative"
email.send()
Run Code Online (Sandbox Code Playgroud)