【问题标题】:Displaying inline images on iPhone, iPad在 iPhone、iPad 上显示内嵌图像
【发布时间】:2012-04-23 14:19:39
【问题描述】:

我正在尝试在 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" />

这在 Web 浏览器、Outlook、Thunderbird 中运行良好……除了 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

【问题讨论】:

  • 将您的问题重新标记为更具体的标签,例如“email”或“apple-email”,以找到对它更感兴趣的人,暂时忘记询问“使用 Django 电子邮件创建”。
  • 附加图像(据我所知)是试图让它们默认显示 - 即无需启用“显示来自 foo@bar.com 的所有图像”,因此替代方案是使用您服务器上托管的图像的 URL。图片只会出现一次,但可能需要用户采取行动

标签: ios django email


【解决方案1】:

不同的电子邮件客户端选择以不同的方式呈现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()

【讨论】:

  • 这是否会在 Gmail 中显示电子邮件而不按“显示图像...”?
  • @iAmTheOneAndOnly 我没有测试过,但我对此表示怀疑。即使是这样,这也是 Gmail 中的一个错误,您应该期望他们修复它,所以不要依赖它。
  • 知道如何用 ruby​​ 完成此操作吗? ActionMailer?
猜你喜欢
  • 1970-01-01
  • 2013-09-30
  • 2020-03-24
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 2017-07-27
  • 2014-05-16
相关资源
最近更新 更多