Send HTML emails with django

Send HTML emails with django


Tags: django html email SMTP

Below is a quick snippet on how to send HTML emails with Django. If you have email.html in your template directory, you can do:

from django.core.mail import send_mail, EmailMessage
from django.template.loader import render_to_string
from django.conf import settings

from .models import Subscriber

def send_html_email(to_list, subject, template_name, context, sender=settings.DEFAULT_FROM_EMAIL):
    msg_html = render_to_string(template_name, context)
    msg = EmailMessage(subject=subject, body=msg_html, from_email=sender, bcc=to_list)
    msg.content_subtype = "html"  # Main content is now text/html
    return msg.send()

# for example
def notify_subscribers():
    emails = Subscriber.objects.all().values_list('email', flat=True)
    context = {
        'news': 'We have good news!'
    send_html_email(emails, subject='Good news', 'email.html', context, sender="[email protected]")

If you’re like me and have a hard time designing a perfect email template, try this one: Really Simple Responsive HTML Email Template

Please do not send spam emails with this snippet.