These docs are a work-in-progress and are currently undergoing a major rewrite!

Sending email

Sending email with Django doesn't need to be complicated, but you do need to pick a provider.

There are more, but here are our top picks for sending email (in order):

With all of these providers, you can send email using standard SMTP settings. There are specific Django packages for some providers, but in our experience, you don't really need them unless you need specific features of the provider API.

Environment variables

The SMTP settings can be configured with environment variables.

# Directly matches the Django settings
EMAIL_HOST = "smtp.postmarkapp.com"
EMAIL_PORT = 587  # optional, 587 is default
EMAIL_HOST_USER = "<postmark_server_token>"
EMAIL_HOST_PASSWORD = "<postmark_server_token>"
DEFAULT_FROM_EMAIL = "support@example.com"

In local development, you can leave these out and it will use the django.core.mail.backends.console.EmailBackend.

TemplateEmail

One email feature that comes with Forge is the TemplateEmail. This class renders an email using the Django template engine, and sends it using your email settings.

Here's a basic example (look at the class itself for more options):

from forge.email import TemplateEmail


email = TemplateEmail(
    to="user@example.com",
    subject="Welcome!",
    template="welcome",
    context={"name": "John"},
)
email.send()

The templates work just like your view templates, but are stored in "email" subdirectory.

You need to at least specify an HTML template, which is email/welcome.html in this example:

<!-- email/welcome.html -->
<p>Hi {{ name }}!</p>

<p>Welcome to our app.</p>

Plain text templates are optional and use the .txt extension instead of .html. In this example it would be email/welcome.txt.

<!-- email/welcome.txt -->
Hi {{ name }}!

Welcome to our app.

If you don't create a .txt template, then the plain text version will be automatically generated from the HTML template by using django.utils.html.strip_tags.

Environment variables

There are two additional env variables that are used by TemplateEmail:

DEFAULT_FROM_NAME = "App Name"
DEFAULT_REPLYTO_EMAIL = "noreply@example.com"

You can use them for your own email sending too by importing settings.

from django.conf import settings
from django.core.mail import send_mail

send_mail(
    "Subject here",
    "Here is the message.",
    f"{settings.DEFAULT_FROM_NAME} <{settings.DEFAULT_FROM_EMAIL}>",
    ["to@example.com"],
    fail_silently=False,
)