在iPhone,iPad上显示内嵌图像

时间:2012-04-11 09:24:54

标签: ios django email

我正在尝试使用内嵌图片在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()

在模板中我会像这样引用它:

<img src="cid:image1" />

这在网页浏览器,Outlook,雷鸟......中都可以正常使用,除了OSX,iPad和iPhone上的苹果邮件客户端。图像显示两次。它们正确放置在内联,但它们也附在电子邮件的底部。我的问题是,如何摆脱底部的图像?或者我应该以不同方式处理电子邮件中的图像

参考文献:
http://djangosnippets.org/snippets/1507/
Django: How to send HTML emails with embedded images
creating a MIME email template with images to send with python / django

1 个答案:

答案 0 :(得分: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()