Django Templated Mail

1.1.1 · active · verified Thu Apr 16

Django Templated Mail is a Python library for Django that simplifies sending emails by leveraging Django's powerful template system. It allows developers to define email subject, body (HTML and plain text), and other attributes using standard Django templates. The current version is 1.1.1, and it maintains an active release cadence with regular bug fixes and feature enhancements, particularly for Django version compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a templated email class and send an email using `django-templated-mail`. It sets up minimal Django settings for a runnable example. Remember to create the actual template file (e.g., `my_app/templates/emails/welcome.html`) in your Django project, extending `templated_mail/email.html` and defining `subject`, `html`, and `plain` blocks.

import os
import django
from django.conf import settings
from templated_mail.mail import BaseEmailMessage

# Minimal Django setup for demonstration purposes.
# In a real Django project, these settings would be in your settings.py
# and django.setup() would be handled by manage.py.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

if not settings.configured:
    settings.configure(
        INSTALLED_APPS=['templated_mail'],
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [],
                'APP_DIRS': True, # Allows finding templates in app 'templates' subdirectories
                'OPTIONS': {
                    'debug': True,
                },
            },
        ],
        DEFAULT_FROM_EMAIL='noreply@example.com',
        EMAIL_BACKEND='django.core.mail.backends.console.EmailBackend', # Prints email to console
    )
# Ensure Django is set up *after* settings are configured.
django.setup()

# Define your custom email message class.
# IMPORTANT: You need to create the actual template file in your Django project.
# For example, create 'my_app/templates/emails/welcome.html' with content like:
#
# {% extends "templated_mail/email.html" %}
# {% block subject %}Welcome, {{ user_name }}!{% endblock %}
# {% block html %}<p>Hello {{ user_name }},</p><p>Thank you for joining our service!</p>{% endblock %}
# {% block plain %}{% block subject %}{% endblock %} Hello {{ user_name }}, Thank you for joining our service!{% endblock %}

class WelcomeEmail(BaseEmailMessage):
    # This path assumes 'emails/welcome.html' is found in one of your TEMPLATES DIRS or APP_DIRS
    template_name = 'emails/welcome.html'

# Instantiate and send the email
context_data = {'user_name': 'John Doe'}
email = WelcomeEmail(context=context_data)
email.send(to=['john.doe@example.com'], from_email='noreply@myservice.com')

print("\nEmail sent (output to console). Check your console for details.")

view raw JSON →