multipart/mixed
さまざまな電子メールクライアントが、さまざまな方法でメッセージをレンダリングすることを選択します。
ほとんどのクライアントは、各パートを(「マルチパート」メッセージで)インラインで、電子メールに追加された順序でレンダリングすることを選択します。ただし、画像がtext/html
パーツで参照されている場合、ほとんどのクライアントは、「すべてのパーツのインライン化」プロセスの一部として、後でその画像を再度表示することはありません。
OSXとiOSのAppleMailは、HTMLと画像の間の内部参照に関係なく、メッセージ内の各部分を含まれている順序で表示するという点で異なります。multipart/mixed
これにより、画像がHTML内に一度表示され、メッセージの最後に自動的にインライン化されて表示されます。
解決策は、HTMLアセットと画像アセットを1つ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()