Django: How to send HTML emails with embedded images

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
from functools import lru_cache


@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

Leave a Comment