使用python/django创建包含要发送的图像的MIME电子邮件模板

使用python/django创建包含要发送的图像的MIME电子邮件模板,python,django,email,mime,Python,Django,Email,Mime,在我的web应用程序中,我偶尔使用可重用的邮件程序发送电子邮件,如下所示: user - self.user subject = ("My subject") from = "me@mydomain.com" message = render_to_string("welcomeEmail/welcome.eml", { "user" : user, }) send_mail(subject, message, from, [em

在我的web应用程序中,我偶尔使用可重用的邮件程序发送电子邮件,如下所示:

user - self.user
subject = ("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编码的邮件模板,并在发送时正确呈现内联图像?

更新

非常感谢你在我回答这个老问题将近5年后再次提出这个问题

我当时的指示不再有效了。我怀疑在这几年中Django有了一些改进,这意味着
send\u mail()
强制使用纯文本。无论您在内容中添加了什么,它都将以纯文本的形式提供

最近的一篇文章解释说,
send\u mail()
实际上只是方便创建
django.core.mail.EmailMessage
类的实例,然后对该实例调用
send()
EmailMessage
为body参数添加了以下注释,这解释了我们在2014年看到的结果:

正文:正文文本。这应该是一条纯文本消息

。。。稍后在文档中

默认情况下,EmailMessage中body参数的MIME类型为“text/plain”。这是一个很好的做法

很公平(我承认我没有花时间调查为什么2009年的指令有效——我确实在2009年测试过它们——或者是在它改变的时候)。Django确实提供了和一个
Django.core.mail.EmailMultiAlternations
类,使发送同一消息的纯文本和HTML表示更加容易

这个问题的情况略有不同。我们不寻求附加一个替代品本身,而是将相关部分附加到一个替代品上。在HTML版本中(不管您是否拥有或省略纯文本版本),我们希望嵌入一个图像数据部分。不是内容的替代视图,而是HTML正文中引用的相关内容

发送嵌入式图像仍然是可能的,但我看不到使用
send\u mail
的简单方法。是时候放弃便利功能,直接实例化
电子邮件了

下面是对上一个示例的更新:

from django.core.mail import EmailMessage
from 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()
从django.core.mail导入EmailMessage
从email.mime.image导入MIMEImage
从email.mime.multipart导入MIMEMultipart
从email.mime.text导入MIMEText
#加载要以字节形式发送的图像
img_data=open('logo.jpg','rb')。read()
#创建一个包含HTML的“相关”消息容器
#信息和图像。这些是“相关的”(而不是“备选方案”)
#因为它们是HTML消息的不同、独特的部分,
#不是相同内容的备选(html与纯文本)视图。
html\u part=MIMEMultipart(\u subtype='related')
#用HTML创建主体。请注意,由于图像是内联的,因此
#引用URL cid:myimage。。。你应该注意做些什么
#“myimage”独一无二
body=MIMEText(“Hello

”,\u subtype='html') html_part.attach(正文) #现在为图像创建MIME容器 img=mimimage(img_数据,'jpeg') img.add_标题('Content-Id','')#尖括号很重要 img.add_头(“内容处置”,“内联”,filename=“myimage”)#David Hess建议进行此编辑 html_part.attach(img) #配置并发送电子邮件 #注意,我们为主体传递None(第二个参数)。你可以传递纯文本 #为该邮件创建替代部分的步骤 msg=EmailMessage('主题行',无,'foo@bar.com', ['bar@foo.com']) msg.attach(html#u部分)#附加原始MIMEBase子体。这是EmailMessage上的公共方法 msg.send()

2009年的原始回复:

要发送带有嵌入图像的电子邮件,请使用python的内置电子邮件模块构建MIME部分

应采取以下措施:

from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Load the image you want to send at bytes
img_data = open('logo.jpg', 'rb').read()

# Create a "related" message container that will hold the HTML 
# message and the image
msg = 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')
msg.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
msg.attach(img)

send_mail(subject, msg.as_string(), from, [to], priority="high")
从email.mime.image导入MIMEImage
从email.mime.multipart导入MIMEMultipart
从email.mime.text导入MIMEText
#以字节加载要发送的图像
img_data=open('logo.jpg','rb')。read()
#创建一个包含HTML的“相关”消息容器
#信息与形象
msg=MIMEMultipart(_subtype='related')
#用HTML创建主体。请注意,由于图像是内联的,因此
#引用URL cid:myimage。。。你应该注意做些什么
#“myimage”独一无二
body=MIMEText(“Hello

”,\u subtype='html') 附加信息(正文) #现在为图像创建MIME容器 img=mimimage(img_数据,'jpeg') img.add_标题('Content-Id','')#尖括号很重要 附加消息(img) 发送邮件(主题,msg.as_string(),发件人,[收件人],优先级=“高”)

实际上,您可能希望将HTML与纯文本选项一起发送。在这种情况下,使用MIMEMultipart创建“相关”mimetype容器作为根。然后创建另一个具有子类型“alternative”的MIMEMultipart,并将一个MIMEText(子类型html)和一个MIMEText(子类型纯文本)附加到替换零件。然后将图像附加到相关的根。

我在Django 1.10上遇到了Jarret的配方问题-在附加MIME数据的各种方法中,都出现了MIME和编码错误

下面是一个简单的多部分事务模板,用于嵌入django 1.10上的
优惠券\u图像
文件对象的电子邮件:

from django.core.mail import EmailMultiAlternatives
from email.mime.image import MIMEImage

def send_mail(coupon_image):
    params = {'foo':'bar'} # create a template context
    text_body = render_to_string('coupon_email.txt', params)
    html_body = render_to_string('coupon_email.html', params)
    img_data = coupon_image.read() #should be a file object, or ImageField
    img = MIMEImage(img_data)
    img.add_header('Content-ID', '<coupon_image>')
    img.add_header('Content-Disposition', 'inline', filename="coupon_image")

    email = EmailMultiAlternatives(
        subject="Here's your coupon!",
        body=text_body,
        from_email='noreply@example.com',
        to=['someone@example.com',]
    )

    email.attach_alternative(html_body, "text/html")
    email.mixed_subtype = 'related'
    email.attach(img)

    email.send(fail_silently=False)
从django.core.mail导入电子邮件
从email.mime.image导入MIMEImage
def发送邮件(优惠券图片):
params={'foo':'bar'}创建模板上下文
text_body=render_to_string('coupon_email.txt',params)
html\u body=呈现到字符串('coupon\u email.html',第