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

时间:2010-09-24 13:51:58

标签: html django image email

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

非常感谢任何一个例子。

5 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分: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">'

答案 2 :(得分: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

答案 3 :(得分: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',
            'from@example.com',
            ['to1@example.com', 'to2@example.com'],
            ['bcc@example.com'],
            reply_to=['another@example.com'],
            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()

答案 4 :(得分:0)

我已经尝试了以下代码,并且可以正常工作。

代码:

msg = EmailMessage()

# generic email headers
msg['Subject'] = 'Welcome'
msg['From'] = 'abc@gmail.com'
recipients = ['abc@gmail.com']

# set the plain text body
msg.set_content('This is a plain text body.')

# now create a Content-ID for the image
image_cid = make_msgid(domain='')
# if `domain` argument isn't provided, it will
# use your computer's name

# set an alternative html body
msg.add_alternative("""\
    <html>
   <body>
      <table border='0' cellpadding='1' cellspacing='0' width='800'>
         <tbody>
            <tr>
               <td height='506'>
                  <table border='0' cellpadding='0' cellspacing='0' width='600'>
                     <tbody>
                        <tr>
                           <td valign='top'>
                              <img height='190' src="cid:{image_cid}" width='800'  tabindex='0'>
                           </td>
                        </tr>
                        <tr>
                           <td height='306' valign='top'>
                              <table cellpadding='0' cellspacing='20' width='800'>
                                 <tbody>
                                    <tr>
                                       <td align='left' height='804' style='font-family:arial,helvetica,sans-serif;font-size:13px' valign='top'>
                                          Hi {name},<br><br>
                                          Welcome!
                                       </td>
                                    </tr>
                                 </tbody>
                              </table>
                           </td>
                        </tr>
                     </tbody>
                  </table>
               </td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
""".format(image_cid=image_cid[1:-1],name='ABC'), subtype='html')
# image_cid looks like <long.random.number@xyz.com>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off

# now open the image and attach it to the email
with open('/path/image.jpg', 'rb') as img:
    # know the Content-Type of the image
    maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')

    # attach it
    msg.get_payload()[1].add_related(img.read(),
                                     maintype=maintype,
                                     subtype=subtype,
                                     cid=image_cid)
server = smtplib.SMTP(host=<hostname>, port=25)

server.starttls()
# send the message via the server.
server.sendmail(msg['From'], recipients, msg.as_string())

server.quit()
相关问题