Howto send html email with embedded image in Django

Hi everyone,

here is another Django tip, a small snippet of code for sending HTML email with an embedded image. This code also handles plain text variant of email.

That is all and as always, any improvement ideas are welcomed.


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

recipient = ""
sender = "" # 
image_path = '/home/webpage/my_image.png'
image_name = Path(image_path).name

subject = "I am sending you nice image."
text_message = f"Email with a nice embedded image {image_name}."

html_message = f"""
<!doctype html>
    <html lang=en>
            <meta charset=utf-8>
            <title>Some title.</title>

            Here is my nice image.<br>
            <img src='cid:{image_name}'/>

# the function for sending an email
def send_email(subject, text_content, html_content=None, sender=sender, recipient=recipient, image_path=None, image_name=None):
    email = EmailMultiAlternatives(subject=subject, body=text_content, from_email=sender, to=recipient if isinstance(recipient, list) else [recipient])

    if all([html_content,image_path,image_name]):
        email.attach_alternative(html_content, "text/html")
        email.content_subtype = 'html'  # set the primary content to be text/html
        email.mixed_subtype = 'related' # it is an important part that ensures embedding of an image 

        with open(image_path, mode='rb') as f:
            image = MIMEImage(
            image.add_header('Content-ID', f"<{image_name}>")


# send an test email
send_email(subject="TEST", text_content=text_message, html_content=html_message, sender=sender, recipient=recipient, image_path=image_path, image_name=image_name)