栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

创建带有图像的MIME电子邮件模板,以使用python / django发送

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

创建带有图像的MIME电子邮件模板,以使用python / django发送

这个问题的情况略有不同。我们并不是要寻求本身的替代,而是要将相关的部分附加到替代之一。在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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/391536.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号