Django has a built-in mail framework. You tell it which SMTP server to use in settings.py, then call send_mail() or build an EmailMultiAlternatives for HTML and attachments. Everything that sends mail in Django, including the password reset views, goes through the same configuration. You can also skip SMTP and call an email API directly.
Option 1: SMTP with Django’s mail framework
Django 6.1 and later: MAILERS
Django 6.1 added the MAILERS setting, which replaces the separate EMAIL_* settings:
# settings.py
import os
MAILERS = {
"default": {
"BACKEND": "django.core.mail.backends.smtp.EmailBackend",
"OPTIONS": {
"host": "smtp.mailcandor.com",
"port": 587,
"use_tls": True,
"username": "mailcandor",
"password": os.environ["MAILCANDOR_KEY"],
"timeout": 10,
},
},
}
DEFAULT_FROM_EMAIL = "Acme <hello@acme.com>"
SERVER_EMAIL = "alerts@acme.com"
use_tls means STARTTLS on port 587. For port 465, use "use_ssl": True instead; never set both. DEFAULT_FROM_EMAIL is the sender when you pass None as from_email, and SERVER_EMAIL is the sender for error reports to ADMINS.
Django 6.0, 5.2 and earlier: EMAIL_* settings
# settings.py
import os
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.mailcandor.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "mailcandor"
EMAIL_HOST_PASSWORD = os.environ["MAILCANDOR_KEY"]
EMAIL_TIMEOUT = 10
DEFAULT_FROM_EMAIL = "Acme <hello@acme.com>"
These still work in 6.1, but they are deprecated there and only used when MAILERS is not defined.
In development, swap the backend for django.core.mail.backends.console.EmailBackend to print emails to the terminal instead of sending them.
Send a plain email
from django.core.mail import send_mail
send_mail(
"Your login code",
"Your code is 481 203",
None, # uses DEFAULT_FROM_EMAIL
["sam@example.com"],
)
Optional arguments such as html_message and fail_silently must be passed by keyword in current Django; passing them by position is deprecated.
Send HTML from a template
from django.core.mail import send_mail
from django.template.loader import render_to_string
context = {"name": "Sam", "code": "481 203"}
send_mail(
"Your login code",
render_to_string("emails/login_code.txt", context),
None,
["sam@example.com"],
html_message=render_to_string("emails/login_code.html", context),
)
Django sends both parts, so clients that cannot show HTML fall back to the text template.
HTML with an attachment
For attachments, CC, reply-to or custom headers, build the message yourself:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
context = {"invoice": invoice}
msg = EmailMultiAlternatives(
subject=f"Invoice {invoice.number}",
body=render_to_string("emails/invoice.txt", context),
from_email="Acme Billing <billing@acme.com>",
to=[invoice.customer_email],
reply_to=["support@acme.com"],
)
msg.attach_alternative(render_to_string("emails/invoice.html", context), "text/html")
msg.attach_file(invoice.pdf.path)
msg.send()
Password reset emails
Django’s PasswordResetView sends through the same configuration, using DEFAULT_FROM_EMAIL as the sender unless you set from_email on the view. If reset emails do not arrive, check that SMTP is configured: without it, Django tries a mail server on localhost, which usually does not exist in production.
Option 2: call an email API
If you want delivery events and safe retries, call an email API from a helper. This uses requests and Mailcandor’s REST API:
# emails.py
import os
import requests
from django.template.loader import render_to_string
def send_login_code(user, code):
context = {"name": user.first_name, "code": code}
resp = requests.post(
"https://api.mailcandor.com/v1/emails",
headers={
"Authorization": f"Bearer {os.environ['MAILCANDOR_KEY']}",
"Idempotency-Key": f"login-code-{user.pk}-{code}",
},
json={
"from": "Acme <hello@acme.com>",
"to": user.email,
"subject": "Your login code",
"html": render_to_string("emails/login_code.html", context),
"text": render_to_string("emails/login_code.txt", context),
},
timeout=10,
)
resp.raise_for_status()
return resp.json()["id"]
The Idempotency-Key header means a retry after a timeout does not send a second code. The returned id lets you match webhook events, such as a bounce, back to the user.
Django’s own send_mail() and the password reset views still use your SMTP settings, so many projects use both: the SMTP relay for built-in Django mail and the API for their own emails, with the same key.
Sending without blocking the request
Both options wait for a network round trip. For a single email after a form submit this is fine. For anything slower or in bulk, run the send in a background worker such as Celery, or with Django’s tasks framework (added in 6.0) and a backend that runs a worker, and return the response straight away.
Using Gmail with Django
For testing you can use smtp.gmail.com on port 587 with TLS and an app password. Gmail is built for personal mail and limits sending, so do not use it for production password resets. See the Gmail SMTP settings guide.
Testing email in Django
Django’s test runner swaps in the in-memory backend automatically, so tests never send real mail. Every message lands in django.core.mail.outbox:
from django.core import mail
from django.test import TestCase
class SignupTests(TestCase):
def test_sends_welcome_email(self):
self.client.post("/signup/", {"email": "sam@example.com"})
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, "Welcome to Acme")
For the API helper, mock requests.post in tests instead.
Common errors
SMTPAuthenticationError: wrong username or password. With Mailcandor the username ismailcandorand the password is your API key.ConnectionRefusedErrorto localhost: no mail settings were loaded, so Django fell back to a local server.- SSL wrong version number: TLS mode and port do not match. Use TLS with 587 or SSL with 465, never both.
Which should you choose?
| Django SMTP backend | Email API | |
|---|---|---|
| Setup | Settings only | A helper function |
| Built-in Django mail (password reset, admin errors) | Yes | No, unless you write a custom backend |
| Safe retries | Not built in | Idempotency keys |
| Delivery events | Usually none | Webhooks per email id |
Before you send: verify your domain
Whatever you choose, the domain in your sender address needs SPF, DKIM and DMARC records, or receiving servers will treat the mail as suspicious. Add your domain with your provider and publish the records it gives you. The SPF, DKIM and DMARC guide explains each one.