Creating Email Templates with Django

Django is a powerful Python web framework that makes it easy to build web applications. One of the many great features of Django is its robust email sending capabilities. With Django, you can configure email backends and create HTML emailTemplates that can be reused throughout your application. In this blog post, we’ll walk through how to create HTML email templates in Django and send templated emails.

First and foremost, let’s discuss why using templates for emails in Django is so useful. Sending emails is a common task for most web apps. You might need to send account confirmation emails, password reset emails, invoice emails, and more. Crafting unique HTML emails for every single scenario can be tedious and time-consuming. This is where templates come in handy! With templates, you can create your base email HTML once and reuse it for every email.

Configuring Email Settings in Django

Before diving into creating templates, we need to configure Django’s email backend settings. This tells Django how to send emails. The most common approach is to use SMTP and connect Django to an external email service like Mailgun, SendGrid, Amazon SES, or your own SMTP server.

You can specify the email backend settings in Django’s settings.py file. Here’s an example using SMTP with Mailgun:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mailgun.org'  
EMAIL_HOST_USER = 'your-mailgun-username'
EMAIL_HOST_PASSWORD = 'your-mailgun-password'
EMAIL_PORT = 587 
EMAIL_USE_TLS = True

This connects Django to Mailgun for sending emails. Make sure to use your own Mailgun credentials. You can use a similar approach for other SMTP providers.

Creating Email Templates in Django

After configuring your email backend, you can start creating templates. Email templates in Django are just normal Django templates that live under a templates/registration/ directory in your app.

For instance, here’s an example email_template.html under templates/registration/:

<!DOCTYPE html>
<html>
<head>
<title>My Email Template</title>
</head>
<body>

<p>Hi {{ name }},</p>

<p>This is a test email template from my Django app. Welcome!</p>

<p>Thanks,<br>  
The App Team
</p>

</body>
</html>

This is a basic HTML template that we can reuse for all emails. Note we can insert variables like {{ name }} that get replaced dynamically when sending emails.

Sending Templated Emails in Django Views

Now that the template is created, using it in the views is simple. First, import render_to_string to render the template as a string:

from django.core.mail import EmailMultiAlternatives 
from django.template.loader import render_to_string

# Render template as a string
html_content = render_to_string('registration/email_template.html', {'name': 'John'})

After that, construct an EmailMultiAlternatives instance, attach the rendered template, and call .send():

msg = EmailMultiAlternatives(
subject='Test Email',
body='This is a test',
from_email='[email protected]',
to=['[email protected]']
)
msg.attach_alternative(html_content, 'text/html')

msg.send()

The templated email will now send!

Best Practices When Creating Email Templates

Here are some tips for creating effective emailTemplates in Django:

  • Use table-based layouts instead of CSS float/flexbox for maximum email client compatibility
  • Inline your CSS rather than using stylesheets to avoid issues
  • Avoid using <div> tags where possible, tables are better supported
  • Test your templates across multiple clients like Gmail, Outlook, Apple Mail
  • Keep templates simple – avoid complex nested tables, fancy styling, huge images
  • Optimize and minify HTML – remove unnecessary whitespace, comments, etc
  • Leverage Django’s template inheritance to create reusable base templates
  • Consider using an email framework like Zurb Ink that handles templates/CSS for you

In Summary

Being able to quickly create and send templated emails is crucial for most Django web apps. With Django’s powerful email backends and template system, sending customizable HTML emails is straightforward. First, configure your email settings. After that, create reusable templates. Finally, use Django’s EmailMultiAlternatives class to send template-based emails in your views. Additionally, follow best practices like using table layouts and testing across clients for the most robust emails. All in all, happy sending!