创建带有图像的MIME电子邮件模板,以使用python / django发送
在我的Web应用程序中,我偶尔会使用可重复使用的邮件发送器应用程序发送电子邮件,如下所示:
user - self.usersubject = ("My subject")
from = "me@mydomain.com"
message = render_to_string("welcomeEmail/welcome.eml", {
"user" : user,
})
send_mail(subject, message, from, [email], priority="high" )
我想发送一封带有嵌入式图像的电子邮件,因此我尝试在邮件客户端中制作邮件,查看源并将其放入模板(welcome.eml)中,但是我一直无法获取它来呈现发送时在邮件客户端中正确显示。
有谁知道我有一种简单的方法来创建带有内嵌图像的mime编码的邮件模板,这些模板在我发送邮件时会正确呈现?
回答:
这个问题的情况略有不同。我们并不是要寻求本身的替代,而是要将相关的部分附加到替代之一。在HTML版本中(是否拥有纯文本版本都没有关系),我们希望嵌入图像数据部分。不是内容的替代视图,而是HTML正文中引用的相关内容。
仍然可以发送嵌入的图像,但是我看不到使用的直接方法send_mail
。现在该放弃便捷功能并EmailMessage
直接实例化一个实例了。
这是对先前示例的更新:
from django.core.mail import EmailMessagefrom email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Load the image you want to send as bytes
img_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" unique
body = MIMEText('<p>Hello <img src="cid:myimage" /></p>', _subtype='html')
html_part.attach(body)
# Now create the MIME container for the image
img = MIMEImage(img_data, 'jpeg')
img.add_header('Content-Id', '<myimage>') # angle brackets are important
img.add_header("Content-Disposition", "inline", filename="myimage") # David Hess recommended this edit
html_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 message
msg = 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 EmailMessage
msg.send()
以上是 创建带有图像的MIME电子邮件模板,以使用python / django发送 的全部内容, 来源链接: utcz.com/qa/421973.html