Chapter 43 · Email delivery and templatesCHAPTER 43
Complete six-part pre-release for review. Three migrations (announcements, the opt-out, an audit action). One earlier query-count test changes (declared). allauth's emails keep allauth's templates for now.
Working towards: Event-day operations (Chapter 46). Reminders sent in the background, a waitlist that offers released places, and check-in that records each attendance once. All milestones
CHAPTER FORTY-THREE
Email delivery and templates
Stage 5: Growing the application (Chapters 35 to 46)
Prerequisites: Chapters 9 to 42, including the Chapter 42 project with its 508 passing tests, Django 6.1’s MAILERS setting and the from address of Chapter 40, the edit page’s save under the lock (Chapters 33 and 38), cancelling an event (Chapter 26), the member’s Profile (Chapters 27 and 31), and transaction.on_commit() (Chapters 33 and 42)
What you’ll build: Mailpit, a pinned local mail catcher with a web inbox; mail settings chosen in .env, a SITE_URL for links, and a deploy check for it; one message function per email, each with a text and an HTML part, sent after commit to one member at a time; five messages (place confirmed, place cancelled, event changed, event cancelled, and organizers’ announcements); a failure path that keeps the place and logs the member’s id; an announcements page with a daily limit and a public-or-private choice; an announcements opt-out on the profile; announcement cards on the event page and a “these members are told” notice on the edit page
Why This Matters
Sai registers for the Python clinic and nothing arrives in her inbox. Raj cancels his place and is not sure it worked. Sam moves the clinic to another room on the morning of the event, and twenty people go to the old one, because Otahque never told them. When Sam cancels an event, nobody hears at all. And Sam would like to send a short note to the people coming: “Bring a laptop.”
Email is how Otahque reaches members who are not looking at it. That makes it powerful and easy to get wrong. A message sent too early describes a change that was rolled back. A message to forty people in one To: line shows each of them the other thirty-nine addresses. A mail server that is down must not cost Sai her place. And a link in an email has to point at the real site, not at a laptop.
By the end of the chapter, you will be able to:
explain what “sent” means, and what Otahque can and cannot know about delivery;
configure Django 6.1’s mailers from .env, with Mailpit catching every message on a laptop;
build multipart emails, text and HTML, from shared templates;
send email only after the change it describes has committed, one message per recipient;
keep a failed send from undoing a registration, and log it without personal data;
test emails with mail.outbox and captureOnCommitCallbacks().
Out of scope: retries, delivery records, and reminders (Chapter 44), a real mail provider with SPF, DKIM, and DMARC (Chapter 63), allauth’s own emails, which keep allauth’s templates for now, and announcements shown live on the page (Chapter 54).
What problem exists? A web application cannot put a message in someone’s inbox. It can only hand the message to a mail server, which passes it on.
What did people do before? Called send_mail() inside the view, often with fail_silently=True, and treated “no error” as “delivered”.
What is it? An email is a text message with headers (From, To, Subject) and a body. A multipart message carries the body twice, as plain text and as HTML, and the reader’s mail app shows the one it can. Django builds it with EmailMultiAlternatives and hands it to a mailer, configured in MAILERS since Django 6.1, which speaks SMTP, the protocol mail servers use, or prints the message, or keeps it in memory for tests.
Why use it? The application stays the same whichever mailer is behind it: Mailpit on a laptop, mail.outbox in tests, a provider in production.
Now let’s use it. Step 2 installs Mailpit; Step 4 sends the first message.
Follow one message in Figure 43.1. Otahque controls only the first step: when send() returns, a mail server has accepted the message. Everything after that, delivery, spam filters, the member opening it, happens elsewhere. So Otahque says “sent”, never “received”, and Chapter 44’s delivery records keep that distinction.
Figure 43.1 — From send() to an inbox, and what Otahque can know.
Tool: Mailpit
Mailpit is a small mail server for developers: it accepts every message on port 1025 and shows it in a web inbox at http://127.0.0.1:8025, as a mail app would, with its HTML, text, and headers. Nothing leaves your computer. It is one program, with no installer, from its GitHub releases page; the book pins version 1.34.0. A real provider replaces it in Chapter 63, by changing one setting.
Under the Hood: Django 6.1’s mailers
Before Django 6.1, one EMAIL_BACKEND setting and a family of EMAIL_* settings described the only mail connection, and code that needed another called get_connection(). Django 6.1 names each configuration in MAILERS, like DATABASES and STORAGES; message.send() uses default. The old settings, get_connection(), and the fail_silently argument are deprecated: they still work in Django 6.1, with a warning, and will be removed. Otahque has used MAILERS since Chapter 40; this chapter adds a second choice of backend.
Five messages, and who gets them
The decisions for this chapter (D43.1 to D43.5) fix the five messages in Figure 43.2. Messages about a member’s own place, and changes to the time or place of their event, are transactional: they exist because of something the member did, and there is no opting out of them. Announcements are different: they come from organizers, so a member can turn them off on their profile. Otahque sends no marketing at all.
Figure 43.2 — Which members get which message.
Table 43.1 — The five messages
Message
Sent when
To
Place confirmed
A member registers
That member
Place cancelled
A cancel changes the place
That member
Event changed
Start, end, zone, or location of a published event changes
Every active place
Event cancelled
The organizers cancel it
Every active place
Announcement
An organizer sends one
Active places, except those who turned them off
After commit, one member at a time
Otahque’s changes happen inside transactions, and a transaction can still roll back after the code that sends an email has run. Figure 43.3 shows the result: an email about a place that does not exist. So every message is sent with transaction.on_commit(), through a small helper, after_commit(). If the transaction commits, the email goes; if it rolls back, nothing is sent.
Figure 43.3 — After commit, not before.
Each message is addressed to one member. A message to many people in one To: line shows every address to every recipient, which in Otahque would leak who is coming to an event. One message per member also means one failure affects one member, and is logged as such.
In practice: a failure that changes nothing
Situation. Mailpit is not running, or later, the provider is down, when Sai registers.
Application.send() catches the mail server’s error, logs it with Sai’s member id, and returns. Sai keeps her place and sees “You have a place.” The log line has no email address: logs are kept longer and read by more people than the database (Chapter 39).
Consideration. The message is lost. Chapter 44 records each message and retries it; for this chapter, the log is the record.
Start from Chapter 42, in the folder containing manage.py, with Otahque on PostgreSQL 18, 508 passing tests, and the work committed (the last commit is “Add covers, a gallery, and member photos”). No Python package is new. One program is: Mailpit, downloaded once in Step 2 and run in a second terminal. Three migrations are new, in events, accounts, and audit. The new files are events/emails.py, two email templates, two event templates, five test modules, and a design note. The settings, .env.example, the checks and their tests, the models, forms, views, and URLs of events, the registrations views, the profile’s model, form, and view, the audit actions, the event and edit pages, the stylesheet, and one earlier test change. The visible result: every message arrives in Mailpit’s inbox, organizers can write to the members coming, and the event page shows public announcements. The chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
The usual first email in a tutorial is one line in the view, after the save: send_mail('You have a place', text, None, [request.user.email], fail_silently=True). It works on the console backend in a minute. It also sends before a transaction commits, hides every failure, sends plain text only, and builds its link from whatever host the request came from, if it builds one at all. In Django 6.1, fail_silently is deprecated too. Steps 3 to 8 replace that line with one place that does each of these properly.
The Django Way
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 508 test(s).
Creating test database for alias 'default'...
...
Ran 508 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Add covers, a gallery, and member photos
Step 2: Install and start Mailpit
Mailpit lives outside the project: it is a tool on your computer, like PostgreSQL, not a package of Otahque’s. Download version 1.34.0 from https://github.com/axllent/mailpit/releases/tag/v1.34.0: on Windows mailpit-windows-amd64.zip, on a Mac with Apple silicon mailpit-darwin-arm64.tar.gz, on Linux mailpit-linux-amd64.tar.gz. GitHub shows each file’s SHA-256 checksum beside it. Check yours before unpacking; on Windows the zip’s checksum is 8f080d41374bf22686606374a0a483c8563c1bf29ae078179792392ff8c911d7.
shasum -a 256 mailpit-darwin-arm64.tar.gz
mkdir -p ~/tools/mailpit
tar -xzf mailpit-darwin-arm64.tar.gz -C ~/tools/mailpit
Then, in the Mailpit folder, check the version:
Windows PowerShell, in $HOME\tools\mailpit
.\mailpit.exe version
Git Bash, macOS, or Linux, in ~/tools/mailpit
./mailpit version
Output
...\mailpit.exe v1.34.0 compiled with go1.27.4 on
windows/amd64
Start it in a second terminal, and leave it running while you work. The two addresses keep it on your own computer: by default Mailpit listens on every network interface, and anyone on the same network could read your test emails.
Open http://127.0.0.1:8025: an empty inbox. Stop Mailpit with Ctrl+C when you finish for the day; it keeps messages in memory only.
Step 3: Mail settings from .env, and links that point somewhere
Links in emails must be absolute, and an email sent by a background task in Chapter 44 has no request to take the site’s address from. So the address is a setting. In config/settings.py, below SUPPORT_EMAIL:
config/settings.py
# Where links in emails point (Chapter 43). An email sent by
# a background task has no request to take it from.
SITE_URL = config('DJANGO_SITE_URL',
default='http://127.0.0.1:8000')
and the MAILERS setting becomes a choice:
config/settings.py
# Chapter 43: on a laptop, Mailpit catches every message:
# start it, and set DJANGO_MAILER=mailpit in .env. Without
# it, the console prints each message instead. A real
# provider replaces both at deployment (Chapter 63).
if config('DJANGO_MAILER', default='console') == 'mailpit':
MAILERS = {
'default': {
'BACKEND': (
'django.core.mail.backends.smtp.EmailBackend'
),
'OPTIONS': {'host': '127.0.0.1', 'port': 1025,
'timeout': 5},
},
}
else:
MAILERS = {
'default': {
'BACKEND': (
'django.core.mail.backends.console.'
'EmailBackend'
),
},
}
OPTIONS passes host, port, and timeout to Django’s SMTP backend; the timeout stops a send from waiting forever on a mail server that does not answer. Add the two new names to .env.example, below DJANGO_FROM_EMAIL:
.env.example
# Where emails are delivered on this computer: mailpit, when
# Mailpit is running, or console (Chapter 43).
DJANGO_MAILER=console
# The address links in emails start with; check --deploy
# warns while it is this computer's (Chapter 43).
DJANGO_SITE_URL=http://127.0.0.1:8000
and add DJANGO_MAILER=mailpit to your own .env. Leave DJANGO_SITE_URL out: the default is right for your computer. On a server it must not be, so Otahque’s deploy checks get a third. The tests first, in config/tests/test_checks.py: change the docstring of DeployCheckTests to “otahque.W002 to W004 describe production settings.”, and replace test_they_run_only_with_deploy with:
The deploy test now sets SITE_URL itself, so a value in your .env cannot change its result.
Terminal
uv run python manage.py test config.tests.test_checks
Output
Found 10 test(s).
Creating test database for alias 'default'...
ERROR: test_a_real_site_url
AttributeError: module 'config.checks' has no attribute
'check_site_url'. Did you mean: 'check_admin_url'?
ERROR: test_this_computers_site_url
AttributeError: module 'config.checks' has no attribute
'check_site_url'. Did you mean: 'check_admin_url'?
FAIL: test_they_run_only_with_deploy
AssertionError: 'otahque.W004' not found in 'System check
identified some issues:\n\nWARNINGS:\n?: (otahque.W002)
The admin is at /admin/, the first address an attacker
tries.\n\tHINT: Set DJANGO_ADMIN_URL to a path that is
hard to guess (Chapter 23).\n?: (otahque.W003) Emails
would be sent from webmaster@localhost, which nobody
reads.\n\tHINT: Set DJANGO_FROM_EMAIL to an address
members can reply to.\n\nSystem check identified 2 issues
(0 silenced).\n'
Ran 10 tests in ...s
FAILED (failures=1, errors=2)
In config/checks.py, below DJANGO_FROM_EMAIL:
config/checks.py
# Otahque's own default for SITE_URL (Chapter 43).
LOCAL_SITE_URL = 'http://127.0.0.1:8000'
and at the end:
config/checks.py
@register('otahque', deploy=True)
def check_site_url(app_configs, **kwargs):
"""Warn when links in emails would point to a laptop."""
if settings.SITE_URL != LOCAL_SITE_URL:
return []
return [Warning(
f'Links in emails would point to {LOCAL_SITE_URL}.',
hint='Set DJANGO_SITE_URL to the address members '
'use, such as https://otahque.tech.',
id='otahque.W004',
)]
Terminal
uv run python manage.py test config.tests.test_checks
Output
Found 10 test(s).
Creating test database for alias 'default'...
...
Ran 10 tests in ...s
OK
Django has a command that sends one test message through the default mailer. With Mailpit running:
Terminal
uv run python manage.py sendtestemail sam@example.org
It prints nothing; Mailpit’s inbox shows “Test email from ...”. And the deploy checks now say what a server would need:
Terminal
uv run python manage.py check --deploy --tag otahque
Output
System check identified some issues:
WARNINGS:
?: (otahque.W002) The admin is at /admin/, the first address
an attacker tries.
HINT: Set DJANGO_ADMIN_URL to a path that is hard to
guess (Chapter 23).
?: (otahque.W003) Emails would be sent from
webmaster@localhost, which nobody reads.
HINT: Set DJANGO_FROM_EMAIL to an address members can
reply to.
?: (otahque.W004) Links in emails would point to
http://127.0.0.1:8000.
HINT: Set DJANGO_SITE_URL to the address members use,
such as https://otahque.tech.
System check identified 3 issues (0 silenced).
Step 4: One message, two parts
Every Otahque email has the same shape: a greeting, a few paragraphs, and a link to the event page. So one pair of templates serves all five messages, and each message is a function that chooses its words. The text part, templates/emails/message.txt:
templates/emails/message.txt
{% autoescape off %}Hello {{ member.display_name }},
{% for line in lines %}
{{ line }}
{% endfor %}
Open the event page: {{ link }}
{{ site_name }}
{% endautoescape %}
autoescape off matters here: in a text email, & must stay &, not become &. The HTML part, templates/emails/message.html, keeps autoescaping on, so a display name such as <b>Sai</b> is shown, never obeyed:
templates/emails/message.html
{# Every Otahque email, as HTML (Chapter 43). Mail apps #}
{# ignore stylesheets, so styles are on the elements. #}
<!doctype html>
<html lang="en">
<body style="margin:0; padding:24px; background:#f3f5f8;
font-family:Arial, sans-serif; color:#1f2937;">
<div style="max-width:560px; margin:0 auto; padding:24px;
background:#ffffff; border-radius:8px;
border:1px solid #d7dde5;">
<p style="margin:0 0 16px; font-weight:bold;
color:#14284b;">{{ site_name }}</p>
<p>Hello {{ member.display_name }},</p>
{% for line in lines %}
<p style="line-height:1.5;">{{ line }}</p>
{% endfor %}
<p style="margin:24px 0 0;">
<a href="{{ link }}"
style="display:inline-block; padding:10px 16px;
background:#0a54d6; color:#ffffff;
border-radius:6px; text-decoration:none;">
Open the event page</a></p>
</div>
</body>
</html>
Mail apps ignore stylesheets and most modern CSS, so the styles are written on the elements themselves, in a narrow centred box. The module that sends them, events/emails.py:
events/emails.py
"""Otahque's emails to members (Chapter 43).
One function per message. Each sends one email to each
member, so nobody sees another member's address, and is
called with after_commit(), once the change it describes
has really been saved.
"""
import logging
import smtplib
from zoneinfo import ZoneInfo
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db import transaction
from django.template.loader import render_to_string
log = logging.getLogger('otahque.email')
# The event fields whose change members are told about.
TOLD = ['starts_at', 'ends_at', 'timezone', 'location']
def after_commit(function, *args):
"""Call function(*args) once the transaction commits."""
transaction.on_commit(lambda: function(*args))
def send(member, subject, lines, path):
"""Send one message to member; return whether it went.
lines are the message's paragraphs; path is the page
its link opens. A failure is logged with the member's
id, not their address, and undoes nothing: the place,
change, or announcement stands.
"""
context = {
'member': member, 'lines': lines,
'link': settings.SITE_URL + path,
'site_name': settings.SITE_NAME,
}
text = render_to_string('emails/message.txt', context)
html = render_to_string('emails/message.html', context)
message = EmailMultiAlternatives(
f'[{settings.SITE_NAME}] {subject}', text,
to=[member.email],
)
message.attach_alternative(html, 'text/html')
try:
message.send()
except (smtplib.SMTPException, OSError):
log.exception('email not sent to member %s: %s',
member.pk, subject)
return False
return True
def when(event):
"""Return the start, in the event's own zone."""
start = event.starts_at.astimezone(
ZoneInfo(event.timezone)
)
return f'{start:%A %d %B %Y, %H:%M} {start.tzname()}'
def place_confirmed(registration):
"""Tell a member they have a place."""
event = registration.event
send(registration.member, f'You have a place: {event}', [
f'You have a place at {event}, {when(event)}, '
f'at {event.location}.',
'If you cannot come, cancel your place on the '
'event page, so someone else can have it.',
], event.get_absolute_url())
def place_cancelled(registration):
"""Tell a member their place is cancelled."""
event = registration.event
send(registration.member, f'Place cancelled: {event}', [
f'Your place at {event} is cancelled.',
'If that was a mistake, register again while places '
'are left.',
], event.get_absolute_url())
send() is the one place an email leaves Otahque. It renders both parts from the same context, so the text and HTML always say the same thing, and addresses the message to one member. message.send() uses the default mailer. The except names the errors a mail server can cause, SMTPException and OSError (a refused connection is an OSError), and logs them with log.exception(), which adds the traceback. when() writes the start in the event’s own zone, because an email has no viewer whose zone Otahque knows. after_commit() wraps transaction.on_commit(), so call sites read as what they mean.
Try one message against your own data. Save this as try_mail.py beside manage.py, run it, and delete it:
try_mail.py
from events.emails import place_confirmed
from registrations.models import Registration
place = Registration.objects.filter(
status='active', event__title='Python clinic 1',
).select_related('event', 'member').first()
place_confirmed(place)
print('Sent to', place.member.display_name)
Terminal
uv run manage.py shell -v 0 -c "exec(open('try_mail.py').read())"
uv run manage.py is a shorter way to write uv run python manage.py: uv runs a .py file with the project’s Python.
Output
Sent to Ines 8
In Mailpit, open the message. The HTML tab shows the box and the button; the Text tab, the plain version; Headers, that it went to one address.
Step 5: Confirmations, after commit
The tests, in events/tests/test_emails.py. A TestCase never commits, so on-commit functions never run on their own; captureOnCommitCallbacks(execute=True) collects them and runs them when its block ends. During tests Django replaces every mailer with its in-memory backend, whose messages wait in mail.outbox: no test ever reaches Mailpit.
events/tests/test_emails.py
"""The emails members get about their places (Chapter 43).
A TestCase never commits, so emails sent after commit are
run with captureOnCommitCallbacks(execute=True). Tests send
to Django's locmem backend: mail.outbox, not Mailpit.
"""
from django.core import mail
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from events.emails import place_confirmed
from registrations.tests.test_registrations import (
soon, verified,
)
def register(client, event):
"""Register the signed-in member through the page."""
return client.post(
reverse('registrations:register', args=[event.pk]))
class PlaceEmailTests(TestCase):
"""Registering and cancelling each send one email."""
@classmethod
def setUpTestData(cls):
cls.sai = verified('sai@example.org')
cls.event = soon()
def setUp(self):
self.client.force_login(self.sai)
def test_a_new_place_is_confirmed(self):
with self.captureOnCommitCallbacks(execute=True):
register(self.client, self.event)
[email] = mail.outbox
self.assertEqual(email.to, ['sai@example.org'])
self.assertEqual(email.subject,
'[Otahque] You have a place: '
'Django clinic')
link = 'http://127.0.0.1:8000' + (
self.event.get_absolute_url())
self.assertIn(link, email.body)
html, kind = email.alternatives[0]
self.assertEqual(kind, 'text/html')
self.assertIn(f'href="{link}"', html)
def test_a_cancelled_place_is_confirmed(self):
place = self.event.register(self.sai, timezone.now())
address = reverse('registrations:cancel',
args=[place.pk])
with self.captureOnCommitCallbacks(execute=True):
self.client.post(address)
[email] = mail.outbox
self.assertIn('Place cancelled', email.subject)
def test_nothing_is_sent_before_commit(self):
with self.captureOnCommitCallbacks() as waiting:
register(self.client, self.event)
self.assertEqual(mail.outbox, [])
self.assertEqual(len(waiting), 1)
def test_names_are_escaped_in_html(self):
self.sai.display_name = '<b>Sai</b>'
self.sai.save()
place = self.event.register(self.sai, timezone.now())
place_confirmed(place)
html = mail.outbox[0].alternatives[0][0]
self.assertIn('<b>Sai</b>', html)
self.assertIn('Hello <b>Sai</b>,', mail.outbox[0].body)
Terminal
uv run python manage.py test events.tests.test_emails
Output
Found 4 test(s).
Creating test database for alias 'default'...
ERROR: test_a_cancelled_place_is_confirmed
ValueError: not enough values to unpack (expected 1, got 0)
ERROR: test_a_new_place_is_confirmed
ValueError: not enough values to unpack (expected 1, got 0)
FAIL: test_nothing_is_sent_before_commit
AssertionError: 0 != 1
Ran 4 tests in ...s
FAILED (failures=1, errors=2)
In registrations/views.py, below the audit.models import:
registrations/views.py
from events import emails
from events.emails import after_commit
In take_place(), keep the new place:
registrations/views.py
place = event.register(request.user, timezone.now(),
answers)
and below messages.success(request, 'You have a place.') add after_commit(emails.place_confirmed, place). say_cancelled() becomes:
registrations/views.py
def say_cancelled(request, registration, changed):
"""Tell the member what their cancel request did."""
if not changed:
messages.info(request,
'This place was already cancelled.')
return
after_commit(emails.place_cancelled, registration)
if registration.is_late():
messages.success(request, 'Place cancelled. It '
'counts as a late cancellation.')
else:
messages.success(request, 'Place cancelled.')
A cancel that changed nothing sends nothing: the member already had that email.
Terminal
uv run python manage.py test events.tests.test_emails
Output
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s
OK
Register for an event in your browser now, and the confirmation arrives in Mailpit.
Step 6: When sending fails
Stop Mailpit with Ctrl+C and register for another event: the page still says “You have a place.”, and the terminal running runserver shows a logged error with a traceback. That is the design: the place is the member’s, and an email about it is a courtesy. The test, in events/tests/test_email_failures.py, uses a mailer that refuses every message:
events/tests/test_email_failures.py
"""When an email cannot be sent (Chapter 43)."""
from django.core.mail.backends.base import BaseEmailBackend
from django.test import TestCase, override_settings
from events.tests.test_emails import register
from registrations.models import Registration
from registrations.tests.test_registrations import (
soon, verified,
)
class BrokenBackend(BaseEmailBackend):
"""A mail server that is not there."""
def send_messages(self, messages):
"""Refuse, as a stopped Mailpit does."""
raise ConnectionRefusedError('nothing on port 1025')
BROKEN = {'default': {
'BACKEND': 'events.tests.test_email_failures.'
'BrokenBackend',
}}
class FailureTests(TestCase):
"""A failed send is logged, and undoes nothing."""
@classmethod
def setUpTestData(cls):
cls.sai = verified('sai@example.org')
cls.event = soon()
def setUp(self):
self.client.force_login(self.sai)
@override_settings(MAILERS=BROKEN)
def test_a_failed_send_keeps_the_place(self):
with self.assertLogs('otahque.email', 'ERROR') as logs:
with self.captureOnCommitCallbacks(execute=True):
register(self.client, self.event)
self.assertTrue(Registration.objects.filter(
event=self.event, member=self.sai).exists())
self.assertIn(f'member {self.sai.pk}', logs.output[0])
self.assertNotIn('sai@example.org', logs.output[0])
Terminal
uv run python manage.py test events.tests.test_email_failures
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
assertLogs() both checks the log and keeps it out of the test output. The test also checks what the log line must not hold: Sai’s address. Start Mailpit again before going on.
Common Error: fail_silently=True
fail_silently=True hides every failure, including a wrong password or a mistyped host, so nothing is sent and nothing says so, for weeks. Django 6.1 deprecates it. Catch the mail server’s errors yourself, log them, and decide what the failure means for the member.
Step 7: The event changed
The members who hold places are needed by several messages, so the query belongs to Event. In events/models.py, add from django.contrib.auth import get_user_model below the settings import, and in Event, above places_taken():
events/models.py
def holders(self):
"""Return the members who hold an active place."""
return get_user_model().objects.filter(
registrations__event=self,
registrations__status='active',
).order_by('pk')
get_user_model() is called inside the method, because accounts.models imports events.models, and the reverse import at the top would make a circle. At the end of events/emails.py, the two event messages:
events/emails.py
def event_changed(event, fields):
"""Tell every holder that the time or place changed."""
lines = [
f'{event} has changed. It now starts {when(event)}, '
f'at {event.location}.',
'Your place is kept. If you can no longer come, '
'cancel it on the event page.',
]
for member in event.holders():
send(member, f'Changed: {event}', lines,
event.get_absolute_url())
def event_cancelled(event):
"""Tell every holder that the event is off."""
lines = [f'{event}, on {when(event)}, is cancelled. '
'The organizers are sorry.']
for member in event.holders():
send(member, f'Cancelled: {event}', lines,
event.get_absolute_url())
Each holder gets their own copy, from one loop. The tests, in events/tests/test_event_emails.py: Sai and Raj hold places, Soni’s place is cancelled.
events/tests/test_event_emails.py
"""Holders hear when their event changes (Chapter 43)."""
from django.core import mail
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from config.helpers import as_sent, in_group
from registrations.tests.test_registrations import (
soon, verified,
)
class EventEmailTests(TestCase):
"""Holders hear about a changed or cancelled event."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.event = soon(capacity=5)
cls.event.add_organizer(cls.sam)
now = timezone.now()
for name in ('sai', 'raj', 'soni'):
place = cls.event.register(
verified(f'{name}@example.org'), now)
place.cancel(now)
def setUp(self):
self.client.force_login(self.sam)
def edit(self, **changes):
"""Save the edit page with changes."""
self.event.refresh_from_db()
data = as_sent(self.event, **changes)
with self.captureOnCommitCallbacks(execute=True):
return self.client.post(
reverse('events:edit', args=[self.event.pk]),
data)
def test_a_new_place_tells_each_holder(self):
self.edit(location='Room 2, Leeds Central Library')
self.assertEqual(
sorted(m.to[0] for m in mail.outbox),
['raj@example.org', 'sai@example.org'])
self.assertIn('Room 2', mail.outbox[0].body)
self.assertEqual(len(mail.outbox[0].to), 1)
def test_a_new_title_tells_nobody(self):
self.edit(title='Django clinic, autumn')
self.assertEqual(mail.outbox, [])
Terminal
uv run python manage.py test events.tests.test_event_emails
Output
Found 2 test(s).
Creating test database for alias 'default'...
FAIL: test_a_new_place_tells_each_holder
AssertionError: Lists differ: [] != ['raj@example.org',
'sai@example.org']
Ran 2 tests in ...s
FAILED (failures=1)
save_edit() already lists the fields that changed, for its audit record; the email uses the same list. In events/views.py, add above from .forms import (:
events/views.py
from . import emails
from .emails import after_commit
and in save_edit(), below the record(...) call:
events/views.py
# Chapter 43: tell members holding places, after
# commit, if the time or the place changed.
told = [name for name in changed if name in emails.TOLD]
if told and event.status == Event.Status.PUBLISHED:
after_commit(emails.event_changed, event, told)
A draft has no places, and a cancelled event has had its email, so only a published event tells anyone.
Terminal
uv run python manage.py test events.tests.test_event_emails
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Step 8: The event cancelled
In event_cancel(), inside the atomic() block, below record(...), add after_commit(emails.event_cancelled, event). The email waits for the same transaction as the cancellation. A test, at the end of EventEmailTests:
events/tests/test_event_emails.py
def test_cancelling_tells_each_holder(self):
with self.captureOnCommitCallbacks(execute=True):
self.client.post(
reverse('events:cancel', args=[self.event.pk]))
self.assertEqual(len(mail.outbox), 2)
self.assertTrue(all('Cancelled:' in m.subject
for m in mail.outbox))
Terminal
uv run python manage.py test events.tests.test_event_emails
Output
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s
OK
Step 9: Turning announcements off
Before anything sends announcements, members get the switch (D43.5). The tests, in accounts/tests/test_opt_out.py:
accounts/tests/test_opt_out.py
"""Turning organizers' announcements off (Chapter 43)."""
from django.test import TestCase
from django.urls import reverse
from accounts.models import Profile
from registrations.tests.test_registrations import verified
class OptOutTests(TestCase):
"""A member turns announcements off on their profile."""
def test_announcements_are_on_by_default(self):
sai = verified('sai@example.org')
self.assertTrue(Profile.of(sai).announcement_emails)
def test_the_profile_saves_the_choice(self):
sai = verified('sai@example.org')
self.client.force_login(sai)
self.client.post(reverse('accounts:profile'), {
'display_name': 'Sai',
})
self.assertFalse(Profile.of(sai).announcement_emails)
Terminal
uv run python manage.py test accounts.tests.test_opt_out
Output
Found 2 test(s).
Creating test database for alias 'default'...
ERROR: test_announcements_are_on_by_default
AttributeError: 'Profile' object has no attribute
'announcement_emails'
ERROR: test_the_profile_saves_the_choice
AttributeError: 'Profile' object has no attribute
'announcement_emails'
Ran 2 tests in ...s
FAILED (errors=2)
In accounts/models.py, in Profile, below photo:
accounts/models.py
# Chapter 43: organizers' announcements may be turned
# off; messages about the member's own place may not.
announcement_emails = models.BooleanField(
'email me announcements', default=True,
)
In accounts/forms.py, in ProfileForm, below website:
accounts/forms.py
announcement_emails = forms.BooleanField(
required=False,
label="Email me organizers' announcements",
help_text='Emails about your own places, and changes '
'to their events, are always sent.',
)
add 'announcement_emails' to the names save() copies, and in accounts/views.py add 'announcement_emails': profile.announcement_emails, to get_initial(). An unticked checkbox sends nothing at all, so a form posted without it saves False, as the second test shows.
Terminal
uv run python manage.py makemigrations -n opt_out accounts
uv run python manage.py migrate
Output
Migrations for 'accounts':
accounts\migrations\0008_opt_out.py
+ Add field announcement_emails to profile
Operations to perform:
Apply all migrations: account, accounts, admin, audit,
auth, contenttypes, events, mfa, registrations, sessions,
socialaccount
Running migrations:
Applying accounts.0008_opt_out... OK
Terminal
uv run python manage.py test accounts.tests.test_opt_out
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Step 10: The Announcement model
In events/models.py, add from datetime import timedelta at the top, and below GALLERY_FULL:
events/models.py
# Announcements per event in any 24 hours (Chapter 43).
ANNOUNCE_LIMIT = 3
ANNOUNCE_FULL = ('This event has sent 3 announcements in the '
'last 24 hours, the most it may. Try later.')
In Event, above places_taken():
events/models.py
def announcement_recipients(self):
"""Return the holders who want announcements.
A member who never opened their profile has no
Profile row, and gets announcements by default.
"""
return self.holders().exclude(
profile__announcement_emails=False,
)
def announce(self, author, body, public):
"""Store an announcement, or raise ValidationError.
Only a published event may announce, at most
ANNOUNCE_LIMIT times in 24 hours, counted under the
lock, so two quick sends cannot both be the fourth.
"""
with transaction.atomic():
event = self.locked()
if event.status != self.Status.PUBLISHED:
raise ValidationError(
'Only a published event can send '
'announcements.'
)
day_ago = timezone.now() - timedelta(days=1)
recent = event.announcements.filter(
sent_at__gt=day_ago
)
if recent.count() >= ANNOUNCE_LIMIT:
raise ValidationError(ANNOUNCE_FULL)
return event.announcements.create(
author=author, body=body, public=public,
)
The limit is counted on the locked row, as Chapter 42 counted gallery photos: two organizers sending at the same moment cannot both send the fourth. exclude(profile__announcement_emails=False) keeps members who have no Profile row, because for them the join finds nothing to compare, and the default is to send. The model, above class OrganizerAssignment:
events/models.py
class Announcement(models.Model):
"""A short message from an event's organizers."""
event = models.ForeignKey(
Event, on_delete=models.CASCADE,
related_name='announcements',
)
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
null=True, related_name='+',
)
body = models.TextField(max_length=1000)
public = models.BooleanField(
'show on the event page', default=False,
help_text='Unticked: emailed to members with places '
'only.',
)
sent_at = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['-sent_at', '-pk']
def __str__(self):
return f'Announcement for {self.event}'
related_name='+' gives the author no reverse accessor: nothing needs “the announcements a member wrote”. SET_NULL keeps an announcement if its author’s account is deleted. Every announcement is recorded in the audit trail too; in audit/models.py, add to Action, below DOWNLOAD_ATTENDEES, the line ANNOUNCE = 'announce', 'Send an announcement'.
Terminal
uv run python manage.py makemigrations -n announcements events
uv run python manage.py makemigrations -n announce_action audit
uv run python manage.py migrate
Output
Migrations for 'events':
events\migrations\0011_announcements.py
+ Create model Announcement
Migrations for 'audit':
audit\migrations\0005_announce_action.py
~ Alter field action on auditevent
Operations to perform:
Apply all migrations: account, accounts, admin, audit,
auth, contenttypes, events, mfa, registrations, sessions,
socialaccount
Running migrations:
Applying audit.0005_announce_action... OK
Applying events.0011_announcements... OK
Step 11: The announcements page
At the end of events/emails.py:
events/emails.py
def announced(announcement):
"""Send an announcement to each holder who wants them."""
event = announcement.event
lines = announcement.body.splitlines() + [
f'From the organizers of {event}. You can stop '
'announcements on your profile page.',
]
for member in event.announcement_recipients():
send(member, f'From the organizers: {event}', lines,
event.get_absolute_url())
The form, at the end of events/forms.py, with Announcement added to its import from .models:
events/forms.py
class AnnouncementForm(forms.ModelForm):
"""What organizers write to members (Chapter 43)."""
class Meta:
model = Announcement
fields = ['body', 'public']
labels = {'body': 'Message'}
help_texts = {
'body': 'Plain text, at most 1,000 characters. '
'Each member gets their own copy.',
}
widgets = {'body': forms.Textarea(attrs={'rows': 5})}
In events/views.py, the import of the forms becomes:
@require_http_methods(['GET', 'POST'])
def event_announcements(request, event_id):
"""Write to the members who hold places, for organizers.
The announcement is stored, recorded, and emailed after
commit, one message to each member who wants them.
"""
event = event_to_manage(request, event_id, Action.ANNOUNCE)
form = AnnouncementForm()
if request.method == 'POST':
form = AnnouncementForm(request.POST)
if form.is_valid():
try:
with transaction.atomic():
sent = event.announce(
request.user, **form.cleaned_data)
record(request.user, Action.ANNOUNCE, event)
after_commit(emails.announced, sent)
except ValidationError as error:
form.add_error(None, error)
else:
messages.success(request, 'Announcement sent.')
return redirect('events:announcements', event.pk)
return render(request, 'events/announcements.html', {
'event': event, 'form': form,
'announcements': event.announcements.all(),
'recipients': event.announcement_recipients().count(),
})
Storing, recording, and scheduling the emails happen in one transaction: a refused announcement records and sends nothing. **form.cleaned_data passes body and public by name. In events/urls.py, below the remove_photo line:
The tests, in events/tests/test_announcements.py: Sai and Soni hold places, and Soni has turned announcements off.
events/tests/test_announcements.py
"""Organizers' announcements (Chapter 43)."""
from django.core import mail
from django.core.exceptions import ValidationError
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from accounts.models import Profile
from audit.models import AuditEvent
from config.helpers import in_group
from events.models import ANNOUNCE_FULL, Event
from registrations.tests.test_registrations import (
soon, verified,
)
def page(event):
"""Return the address of an event's announcements."""
return reverse('events:announcements', args=[event.pk])
class AnnouncementTests(TestCase):
"""Sam writes to the members holding places."""
@classmethod
def setUpTestData(cls):
cls.sam = in_group('sam@example.org', 'Organizers')
cls.raj = in_group('raj@example.org', 'Organizers')
cls.event = soon(capacity=5)
cls.event.add_organizer(cls.sam)
now = timezone.now()
cls.sai = verified('sai@example.org')
cls.soni = verified('soni@example.org')
for member in (cls.sai, cls.soni):
cls.event.register(member, now)
profile = Profile.of(cls.soni)
profile.announcement_emails = False
profile.save()
def setUp(self):
self.client.force_login(self.sam)
def send(self, body='Bring a laptop.', public=False):
"""Send an announcement through the page."""
data = {'body': body}
if public:
data['public'] = 'on'
with self.captureOnCommitCallbacks(execute=True):
return self.client.post(page(self.event), data)
def test_the_page_counts_who_will_get_it(self):
reply = self.client.get(page(self.event))
self.assertContains(reply, '1 member holding')
def test_each_wanting_holder_gets_one_copy(self):
self.send()
[email] = mail.outbox
self.assertEqual(email.to, ['sai@example.org'])
self.assertIn('Bring a laptop.', email.body)
self.assertEqual(
AuditEvent.objects.latest('pk').action, 'announce')
def test_another_organizer_is_refused(self):
self.client.force_login(self.raj)
reply = self.send()
self.assertEqual(reply.status_code, 403)
self.assertEqual(mail.outbox, [])
def test_the_fourth_in_a_day_is_refused(self):
for _ in range(3):
self.send()
reply = self.send()
self.assertContains(reply, ANNOUNCE_FULL)
self.assertEqual(self.event.announcements.count(), 3)
self.assertEqual(len(mail.outbox), 3)
def test_a_draft_cannot_announce(self):
draft = soon(status=Event.Status.DRAFT)
with self.assertRaises(ValidationError):
draft.announce(self.sam, 'Hello', public=False)
Terminal
uv run python manage.py test events.tests.test_announcements
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Step 12: What the pages show
Public announcements appear on the event page, newest first, at most five, in events/templates/events/announcement_cards.html:
events/templates/events/announcement_cards.html
{# Public announcements on the event page (Chapter 43). #}
{% if announcements %}
<section class="space-y-3" aria-labelledby="news">
<h2 id="news" class="text-lg font-semibold">
From the organizers</h2>
{% for item in announcements %}
<article class="announcement-card">
<p class="text-sm">{{ item.sent_at|date:"j F, H:i" }}
{{ item.sent_at|date:"T" }}</p>
<p>{{ item.body|linebreaksbr }}</p>
</article>
{% endfor %}
</section>
{% endif %}
In events/templates/events/detail.html, add {% include "events/announcement_cards.html" %} above the gallery’s include. EventDetailView.get_context_data() adds them:
events/views.py
"""Add the time, links, pictures, news, and panel."""
now = timezone.now()
user = self.request.user
return super().get_context_data(**kwargs) | {
'now': now,
'can_edit': self.object.can_be_edited_by(user),
'photos': self.object.photos.all(),
'announcements': self.object.announcements.filter(
public=True)[:5],
The edit page has said since Chapter 25 that Otahque does not tell members about changes. Now it does, so the note in events/templates/events/edit.html becomes a notice:
events/templates/events/edit.html
{% if taken %}
{# Chapter 43: say who hears about a change. #}
<p class="notice-card">Places taken: {{ taken }}.
{% if event.status == 'published' %}If you change the
time, the time zone, or the place,
the {{ taken }} member{{ taken|pluralize }} holding a
place {{ taken|pluralize:"is,are" }} told by email
when you save.{% endif %}
</p>
{% endif %}
The styles, in static/otahque/source.css, above .form-actions:
def test_only_public_ones_show_on_the_event_page(self):
self.send('Room 2 this week.', public=True)
self.send('The door code is 4512.')
self.client.logout()
reply = self.client.get(self.event.get_absolute_url())
self.assertContains(reply, 'From the organizers')
self.assertContains(reply, 'Room 2 this week.')
self.assertNotContains(reply, '4512')
def test_the_body_is_escaped(self):
self.send('<script>alert(1)</script>', public=True)
reply = self.client.get(self.event.get_absolute_url())
self.assertNotContains(reply, '<script>alert(1)')
html = mail.outbox[0].alternatives[0][0]
self.assertNotIn('<script>', html)
and one at the end of EventEmailTests:
events/tests/test_event_emails.py
def test_the_edit_page_says_who_will_be_told(self):
reply = self.client.get(
reverse('events:edit', args=[self.event.pk]))
self.assertContains(reply, 'the 2 members holding a')
self.assertContains(reply, 'are told by email')
Run them with the rest of the events app’s tests:
Terminal
uv run python manage.py test events
Output
Found 263 test(s).
Creating test database for alias 'default'...
FAIL: test_pages_show_places_left
AssertionError: 5 != 4 : 5 queries executed, 4 expected
Ran 263 tests in ...s
FAILED (failures=1)
The event page reads its public announcements: one query more. The count is the earlier test’s point, so it changes on purpose, in events/tests/test_events.py:
events/tests/test_events.py
# The registration panel counts places again; the
# gallery (Chapter 42) and the public announcements
# (Chapter 43) are read.
with self.assertNumQueries(5):
response = self.client.get(
Terminal
uv run python manage.py test events
Output
Found 263 test(s).
Creating test database for alias 'default'...
...
Ran 263 tests in ...s
OK
The confirmation in Mailpit, and the announcement on the event page, are in Figure 43.4.
Figure 43.4 — A confirmation in Mailpit, and a public announcement.
Step 13: Records
The design note, docs/design/email.md:
docs/design/email.md
# Email (Chapter 43)
Status: proposed for review. Decisions D43.1-D43.5, N43.6
(DECISIONS.md).
## Messages
- Place confirmed: to the member, after registering.
- Place cancelled: to the member, after a cancel that
changed the place.
- Event changed: to every active place, when the start,
end, time zone, or location of a published event
changes. A new title or description tells nobody.
- Event cancelled: to every active place.
- Announcement: from the event's organizers, to every
active place except members who turned announcements
off on their profile.
Each message goes to one member: no address is ever shown
to another member. Each has a text and an HTML part from
the same lines (templates/emails/message.txt and .html).
## Rules
- Sent after commit (transaction.on_commit), so a
rolled-back change sends nothing.
- A failed send is logged with the member's id, not their
address, and undoes nothing. Chapter 44 adds retries.
- Links start with SITE_URL (DJANGO_SITE_URL); check
--deploy warns while it is this computer's (W004).
- Announcements: published events only; at most 3 in 24
hours, counted under the event's lock; recorded as
announce. "Show on the event page" makes one public;
otherwise it is emailed and listed for organizers only.
- No opt-out from messages about a member's own place;
announcements can be turned off (D43.5).
## On a laptop
Mailpit catches every message (DJANGO_MAILER=mailpit,
SMTP 127.0.0.1:1025, inbox http://127.0.0.1:8025). With
DJANGO_MAILER=console, messages are printed instead. The
tests use Django's locmem backend: mail.outbox.
## Not yet
- Retries, delivery records, reminders: Chapter 44.
- A real provider, SPF, DKIM, and DMARC: Chapter 63.
Step 14: Check and commit
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
== python manage.py test --parallel
Found 528 test(s).
System check identified no issues (0 silenced).
Ran 528 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Email members about their places and events"
Output
M .env.example
M accounts/forms.py
A accounts/migrations/0008_opt_out.py
M accounts/models.py
A accounts/tests/test_opt_out.py
M accounts/views.py
A audit/migrations/0005_announce_action.py
M audit/models.py
M config/checks.py
M config/settings.py
M config/tests/test_checks.py
A docs/design/email.md
A events/emails.py
M events/forms.py
A events/migrations/0011_announcements.py
M events/models.py
A events/templates/events/announcement_cards.html
A events/templates/events/announcements.html
M events/templates/events/detail.html
M events/templates/events/edit.html
A events/tests/test_announcements.py
A events/tests/test_email_failures.py
A events/tests/test_emails.py
A events/tests/test_event_emails.py
M events/tests/test_events.py
M events/urls.py
M events/views.py
M registrations/views.py
M static/otahque/site.css
M static/otahque/source.css
A templates/emails/message.html
A templates/emails/message.txt
[main 1a2b3c4] Email members about their places and events
32 files changed, 870 insertions(+), 25 deletions(-)
create mode 100644 accounts/migrations/0008_opt_out.py
create mode 100644 accounts/tests/test_opt_out.py
create mode 100644 audit/migrations/0005_announce_action.py
create mode 100644 docs/design/email.md
create mode 100644 events/emails.py
create mode 100644 events/migrations/0011_announcements.py
create mode 100644
events/templates/events/announcement_cards.html
create mode 100644
events/templates/events/announcements.html
create mode 100644 events/tests/test_announcements.py
create mode 100644 events/tests/test_email_failures.py
create mode 100644 events/tests/test_emails.py
create mode 100644 events/tests/test_event_emails.py
create mode 100644 templates/emails/message.html
create mode 100644 templates/emails/message.txt
If something goes wrong
Table 43.2 — Recovery for Chapter 43
What you see
Likely cause
What to do
ConnectionRefusedError in the runserver terminal
Mailpit is not running
Start it in the second terminal; or set DJANGO_MAILER=console
Nothing in Mailpit, and no error
.env still says console, or has no DJANGO_MAILER
Add DJANGO_MAILER=mailpit and restart runserver
Mailpit: address already in use
Another Mailpit, or another program, has the port
Close the other one; check with the browser at 127.0.0.1:8025
A test finds mail.outbox empty
The send waits for commit
Wrap the request in captureOnCommitCallbacks(execute=True)
Work through Table 43.3 from the folder that holds manage.py, with Mailpit running in a second terminal.
Table 43.3 — Verification checklist for Chapter 43
Check
Command or action
Expected result
Starting point
test --parallel
Found 508 test(s); OK
Mailpit
mailpit version; the inbox at 127.0.0.1:8025
v1.34.0; an empty inbox
Settings and W004
test config.tests.test_checks; sendtestemail; check --deploy --tag otahque
Red; then OK; a test email in Mailpit; W002, W003, W004
One message
try_mail.py
Sent to ...; the message in Mailpit, HTML and text
Confirmations
test events.tests.test_emails
Red; then 4 tests OK
Failures
test events.tests.test_email_failures
Found 1 test(s); OK
Event emails
test events.tests.test_event_emails
Red; then 2, then 3 tests OK
Opt-out
test accounts.tests.test_opt_out; migrate
Red; accounts 0008_opt_out applied; 2 tests OK
Announcements
makemigrations, migrate; test events.tests.test_announcements
events 0011 and audit 0005 applied; 5 tests OK
Pages
test events
Red once, changed on purpose; then OK
All checks
uv run python check.py
== all checks passed; Ran 528 tests
Commit
git log --oneline -1
Email members about their places and events
Not verified
macOS and Linux shells; Mailpit on macOS and Linux; mail apps other than Mailpit's view
Delivery to real inboxes waits for Chapter 63
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 42 checkpoint with a reader’s data, against PostgreSQL 18, with Mailpit 1.34.0 running bound to 127.0.0.1; commands that write files ran once. The project folder, and Mailpit’s, are shortened to ... in printed output. The screenshots were taken in Microsoft Edge, with one sample event, a place for Sai, her confirmation, and one announcement added for the screenshots only and deleted afterwards.
Que. 1 What does it mean when message.send() returns without an error?
Flip to check your answerFold answer back
Answer. A mail server, Mailpit here, accepted the message. It does not mean the member received it, read it, or that it passed their spam filter. Otahque says “sent”, never “received”.
Que. 2 Why are emails sent with after_commit() rather than straight after the save?
Flip to check your answerFold answer back
Answer. The save is inside a transaction that can still roll back. An email sent before the commit could describe a place or a change that never happened; on_commit() sends only once the change is permanent.
Que. 3 Why does every message go to exactly one member?
Flip to check your answerFold answer back
Answer. A message with many addresses in To: shows each recipient every other address, which in Otahque would reveal who is coming to an event. One message per member also keeps a failure to one member.
Que. 4 Sai turns announcements off. Which emails does she still get?
Flip to check your answerFold answer back
Answer. Everything about her own places: confirmations, cancellations, and changes to or cancellation of events she holds a place for. Only organizers’ announcements stop.
Que. 5 Why is SITE_URL a setting, when the request knows the site’s address?
Flip to check your answerFold answer back
Answer. Emails sent from a background task, in Chapter 44, have no request. One setting gives every email the same, correct address, and check --deploy warns (W004) while it is still this computer’s.
Mini-Challenge
D43.1 says a new description tells nobody. Prove it: write a test, in events/tests/test_quiet.py, that saving a new description of a published event with places sends no email.
Hint: inherit from EventEmailTests to reuse its event, its holders, and its edit() helper.
Model answer:
events/tests/test_quiet.py
"""A new description tells nobody (Chapter 43 challenge)."""
from django.core import mail
from events.tests import test_event_emails
# Through the module: a class imported by name would be
# collected and run here too.
class QuietTests(test_event_emails.EventEmailTests):
"""Only the time, zone, and place are told."""
def test_a_new_description_tells_nobody(self):
self.edit(description='Now with pizza.')
self.assertEqual(mail.outbox, [])
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Inheriting runs the parent’s tests again too, which is why five tests ran. The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
message.send() hands a message to a mail server; “sent” is not “received”.
Django 6.1 configures mail in MAILERS; fail_silently and get_connection() are deprecated.
Mailpit catches every message on a laptop, bound to 127.0.0.1, with a web inbox.
One pair of templates, text and HTML, can serve every message; only the HTML part is escaped.
Send after commit, one message per member, and catch the mail server’s errors yourself.
Tests read mail.outbox, and run on-commit functions with captureOnCommitCallbacks(execute=True).
Absolute links come from a setting, guarded by a deploy check.
Key terms
Use Table 43.4 to explain this chapter’s ideas in your own words.
Table 43.4 — Key terms from Chapter 43
Term
Meaning
SMTP
The protocol mail servers use to pass messages on.
Mailer
A named mail configuration in MAILERS.
Multipart email
One message carrying a text and an HTML version.
EmailMultiAlternatives
Django's class for a multipart message.
Transactional email
A message about something the member did.
Mailpit
A local mail catcher with a web inbox.
mail.outbox
The messages Django's test mailer kept.
on_commit()
Runs a function once the transaction commits.
SITE_URL
The site's address, for links in emails.
Opt-out
A member's choice to stop a kind of message.
Readiness checkpoint: you are ready for Chapter 44 when uv run python check.py ends with “all checks passed” and 528 tests, registering in your browser puts a confirmation in Mailpit, stopping Mailpit does not stop registering, Sam can send an announcement that reaches only the members who want it, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 43 work was committed once, in Step 14, as “Email members about their places and events”: the settings and .env.example, the check, the emails module and its templates, the announcement model, page, and opt-out with their three migrations, the views and templates, the styles, the tests, and the design note. Your .env, with DJANGO_MAILER=mailpit, stays out of Git. If you kept the Mini-Challenge, commit it on its own:
Terminal
git add events/tests/test_quiet.py
git commit -m "Check that a new description tells nobody"
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a support report from production and to the design of Chapter 44. They are extension questions, not a gate to the next chapter. Proof files are run with uv run python manage.py shell -v 0 -c "exec(open('NAME').read())" and deleted afterwards.
L1 (Junior): Which emails can a member turn off, and why only those?
What the interviewer is testing: Do you know transactional email from the rest?
Flip to check your answerFold answer back
Perfect answer: Messages about something the member did, or about a place they hold, are transactional: a confirmation, a cancellation, a changed time or room, a cancelled event. Turning those off would leave a member going to the wrong room, so Otahque always sends them and says so on the profile page. Announcements come from organizers, about things the member did not do, so they can be turned off. Marketing, messages to people who never asked, Otahque does not send at all. Laws such as the GDPR and the UK’s PECR draw a similar line, which is one more reason to keep the categories separate in code.
Figure 43.5 — Kinds of email.
Behind the scenes:
Who checks the switch
place_confirmed, place_cancelled always
event_changed, event_cancelled always
announced announcement_recipients()
Code proof: the opt-out tests:
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
Common mistakes:
One “no emails” switch that also stops confirmations and changes.
Treating an organizer’s announcement as transactional because it is about the event.
Follow-up the interviewer might ask:
Should an announcement email have an unsubscribe link? (Yes, eventually: a link to the profile setting; Chapter 59 looks at signed links.)
What if a member has no Profile row? (They get announcements: the default, and the query keeps them.)
L2 (Mid-Level): Predict what happens to an email sent inside a transaction that rolls back
What the interviewer is testing: Can you reason about side effects and transactions?
Flip to check your answerFold answer back
Perfect answer: If the code calls send() directly inside the transaction, the email goes at once, and the rollback cannot recall it: the member is told about a place that does not exist. With after_commit(), the send is only registered with the transaction; a rollback discards it, and a commit runs it. So the email describes exactly what was saved. The cost is that the email is sent after the response in the same request, so a slow mail server still slows the page, which Chapter 44 fixes.
Code proof: the same confirmation, once rolled back and once committed, to the in-memory mailer:
Output
rolled back: 0 sent
committed: 1 sent
Common mistakes:
Sending in a post_save signal, which runs before commit.
Testing with a TestCase and no captureOnCommitCallbacks(), so the test sees no email and passes for the wrong reason.
Follow-up the interviewer might ask:
And outside any transaction? (on_commit() runs the function immediately.)
What if the process dies after commit, before the send? (The email is lost; Chapter 44’s outbox exists for that.)
L3 (Senior): Defend one message per recipient
What the interviewer is testing: Can you weigh privacy and failure against efficiency?
Flip to check your answerFold answer back
Perfect answer: One message with forty addresses in To: or Cc: shows every recipient every address, which tells strangers who is coming to an event; Otahque’s privacy rules forbid that (D31.4). Bcc: hides them, but one rejected address can fail the whole message, and the member sees a message not addressed to them, which spam filters dislike. One message each is private, personal (“Hello Sai”), and fails one member at a time, which Chapter 44 records and retries per member. The cost is more SMTP traffic, which providers handle routinely, and which Chapter 44 moves out of the request.
Figure 43.7 — One message per member.
Behind the scenes:
Recipients per message
To: sai, raj, ... (40) everyone sees everyone
Bcc: 40 hidden, fails together
To: sai | To: raj | ... one each
Code proof: cancelling a demo event, to the in-memory mailer:
Output
18 messages, recipients each: {1}
Common mistakes:
Putting the organizers in Cc: so they see what went out; the announcements page shows them instead.
Building one message and changing to in a loop, which keeps the first member’s name in the body.
Follow-up the interviewer might ask:
How would you send ten thousand? (In tasks, in batches, through a provider’s bulk interface, with a rate limit.)
How do you test it? (len(message.to) == 1 for every message in mail.outbox.)
L4 (Staff): Members report that links in emails open “127.0.0.1”. Diagnose it
What the interviewer is testing: Can you trace a production symptom to configuration?
Flip to check your answerFold answer back
Perfect answer: Every link in an Otahque email starts with SITE_URL. A link to 127.0.0.1 means the server is running with the default, so DJANGO_SITE_URL is missing from the server’s environment. I would confirm with check --deploy, which reports otahque.W004 in exactly this case, set the variable, restart, and send a test message. Then I would ask why the release did not stop on it: the release script should run check --deploy --fail-level WARNING, which Chapter 63 adds. Emails already sent cannot be corrected, so I would tell affected members which page to open.
Figure 43.8 — Diagnosing links that point to a laptop.
System check identified some issues:
WARNINGS:
?: (otahque.W002) The admin is at /admin/, the first address
an attacker tries.
HINT: Set DJANGO_ADMIN_URL to a path that is hard to
guess (Chapter 23).
?: (otahque.W003) Emails would be sent from
webmaster@localhost, which nobody reads.
HINT: Set DJANGO_FROM_EMAIL to an address members can
reply to.
?: (otahque.W004) Links in emails would point to
http://127.0.0.1:8000.
HINT: Set DJANGO_SITE_URL to the address members use,
such as https://otahque.tech.
System check identified 3 issues (0 silenced).
Common mistakes:
Building links from request.get_host(), which a forged Host header can change, and which a task does not have.
Fixing it in the template, so the next message type has the same bug.
Follow-up the interviewer might ask:
Why not the Sites framework? (One value does not need a table and an admin page; N43.6 B, not chosen.)
Could the check be an error? (Not while the tests run with the default; a warning that fails the release is enough.)
L5 (Lead): Defend sending email in the request now, and in tasks next chapter
What the interviewer is testing: Can you defend a deliberate, temporary design?
Flip to check your answerFold answer back
Perfect answer: This chapter settles what each email says, who gets it, and when it may be sent; those rules do not change when the sending moves. Sending in the request, after commit, is the simplest thing that is correct: no worker to run, no queue to watch, and the failure path is already safe. Its costs are known and bounded: a slow mail server slows the page that triggered the email, an announcement to many members takes as long as their sends, and a failure is logged but not retried. Chapter 44 removes exactly those costs, with a delivery record per member and retries, behind the same emails functions. Doing both at once would have mixed two kinds of bug in one chapter.
Table 43.5 — Now and next
Question
Chapter 43
Chapter 44
Where the send runs
In the request, after commit
In a worker
A failure
Logged; lost
Retried, then marked failed
Many recipients
One request waits
Each queued
What it says
emails.py
emails.py, unchanged
Behind the scenes:
What moves, and what stays
after_commit(send ...) -> becomes: queue a delivery
emails.place_confirmed() -> unchanged
Code proof: the failure test, which the next chapter keeps:
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
Common mistakes:
Adding a task queue before the messages are right, so every bug is also a queue bug.
Leaving request-time sending in production for large announcements.
Follow-up the interviewer might ask:
How slow is “slow”? (Measure: time a registration with Mailpit stopped and with it running; Chapter 44 starts there.)
Would you ever keep sending in the request? (For a password reset, perhaps, where the member waits for that one email anyway.)