这个问题的情况略有不同。我们并不是要寻求本身的替代,而是要将相关的部分附加到替代之一。在HTML版本中(是否拥有纯文本版本都没有关系),我们希望嵌入图像数据部分。不是内容的替代视图,而是HTML正文中引用的相关内容。
仍然可以发送嵌入的图像,但是我看不到使用的直接方法
send_mail。现在该放弃便捷功能并
EmailMessage直接实例化一个实例了。
这是对先前示例的更新:
from django.core.mail import EmailMessagefrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText# Load the image you want to send as bytesimg_data = open('logo.jpg', 'rb').read()# Create a "related" message container that will hold the HTML # message and the image. These are "related" (not "alternative")# because they are different, unique parts of the HTML message,# not alternative (html vs. plain text) views of the same content.html_part = MIMEMultipart(_subtype='related')# Create the body with HTML. Note that the image, since it is inline, is # referenced with the URL cid:myimage... you should take care to make# "myimage" uniquebody = MIMEText('<p>Hello <img src="cid:myimage" /></p>', _subtype='html')html_part.attach(body)# Now create the MIME container for the imageimg = MIMEImage(img_data, 'jpeg')img.add_header('Content-Id', '<myimage>') # angle brackets are importantimg.add_header("Content-Disposition", "inline", filename="myimage") # David Hess recommended this edithtml_part.attach(img)# Configure and send an EmailMessage# Note we are passing None for the body (the 2nd parameter). You could pass plain text# to create an alternative part for this messagemsg = EmailMessage('Subject Line', None, 'foo@bar.com', ['bar@foo.com'])msg.attach(html_part) # Attach the raw MIMEbase descendant. This is a public method on EmailMessagemsg.send()


