Django:如何发送带有嵌入图像的HTML电子邮件

问题描述 投票:15回答:4

如何发送包含嵌入图像的HTML电子邮件? HTML应该如何链接到图像?图像应添加为MultiPart电子邮件附件?

任何例子都非常感激。

html django image email
4个回答
8
投票

http://djangosnippets.org/snippets/285/

你必须使用MultiPart和cid:发送带图像的HTML邮件几乎总是一个坏主意。它为您的邮件和smtp服务器提供垃圾邮件点数......


6
投票

请记住,django只提供标准smtplib的包装器 - 我不知道它是否有用,但试着看看这个例子:http://code.activestate.com/recipes/473810-send-an-html-email-with-embedded-image-and-plain-t/

所以我猜你可以使用EmailMessage的标题值来定义这个'image1' - 消息标题是一个值的字典,所以只需添加像{'Content-ID': '<image1>'}这样的东西。

然后使用attach()将文件附加到您的电子邮件中。之后,您可以使用代码生成如下的html消息:

html_content = '<b>Some HTML text</b> and an image: <img src="cid:image1">'

4
投票

我实现了op要求使用django的邮件系统。它会增加它将使用django设置进行邮件发送(包括用于测试的不同子系统等等。我还在开发期间使用mailhog)。这也是相当高的水平:

from django.conf import settings
from django.core.mail import EmailMultiAlternatives


message = EmailMultiAlternatives(
    subject=subject,
    body=body_text,
    from_email=settings.DEFAULT_FROM_EMAIL,
    to=recipients,
    **kwargs
)
message.mixed_subtype = 'related'
message.attach_alternative(body_html, "text/html")
message.attach(logo_data())

message.send(fail_silently=False)

logo_data是一个附加徽标的辅助函数(在这种情况下我想附加的图像):

from email.mime.image import MIMEImage

from django.contrib.staticfiles import finders


@lru_cache()
def logo_data():
    with open(finders.find('emails/logo.png'), 'rb') as f:
        logo_data = f.read()
    logo = MIMEImage(logo_data)
    logo.add_header('Content-ID', '<logo>')
    return logo

0
投票

如果您要发送带有图像作为附件的电子邮件(在我的情况下,它是直接从表单中捕获的图像,在保存后),您可以使用以下代码作为示例:

#forms.py

from django import forms
from django.core.mail import EmailMessage
from email.mime.image import MIMEImage


class MyForm(forms.Form):
    #...
    def save(self, *args, **kwargs):
        # In next line we save all data from form as usual.
        super(MyForm, self).save(*args, **kwargs)
        #...
        # Your additional post_save login can be here.
        #...
        # In my case name of field was an "image".
        image = self.cleaned_data.get('image', None)
        # Then we create an "EmailMessage" object as usual.
        msg = EmailMessage(
            'Hello',
            'Body goes here',
            '[email protected]',
            ['[email protected]', '[email protected]'],
            ['[email protected]'],
            reply_to=['[email protected]'],
            headers={'Message-ID': 'foo'},
        )
        # Then set "html" as default content subtype.
        msg.content_subtype = "html"
        # If there is an image, let's attach it to message.
        if image:
            mime_image = MIMEImage(image.read())
            mime_image.add_header('Content-ID', '<image>')
            msg.attach(mime_image)
        # Then we send message.
        msg.send()
© www.soinside.com 2019 - 2024. All rights reserved.