Send HTML Email with Templates

A snippet for sending HTML emails rendered from templates.


# views.py or utils.py
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings

def send_html_email(subject, to_email, template_name, context):
    html_content = render_to_string(template_name, context)
    msg = EmailMultiAlternatives(subject, '', settings.DEFAULT_FROM_EMAIL, [to_email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
  
Explanation:
  • Use EmailMultiAlternatives for HTML emails with plain text fallback.
  • Render template to string with render_to_string() for HTML content.
Previous snippet
Use LocaleMiddleware
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.