Django: How to send HTML emails with embedded images

前端 未结 5 1764
心在旅途
心在旅途 2020-12-03 03:18

How can I send HTML emails with embedded images? How the HTML should link to the images? The images should be added as MultiPart email attach?

Any example is very ap

5条回答
  •  悲哀的现实
    2020-12-03 03:37

    I achieved what op is asking for using django's mailing system. Upsides it that it'll use django settings for mailing (including a different subsystem for testing, etc. I also use mailhogs during development). It's also quite a bit higher level:

    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 is a helper function that attaches the logo (the image I wanted to attach in this case):

    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', '')
        return logo
    

提交回复
热议问题