Skip to content

Lesson 36 of 59Product features

Sending Email from a Backend

Send transactional email from FastAPI reliably: a provider, SPF, DKIM and DMARC, safe templates, an outbox with retries, and bounce webhooks.

19 min read0/4 questions

Email looks like the easiest feature in the backlog: build a string, call smtplib, done. Then the bug reports arrive. Password reset emails land in spam at Gmail. Sign-up takes eight seconds because the SMTP server is slow, and fails completely when it is down. A retry sends the same receipt three times. Someone discovers they can make your reset email link to their own domain. Nobody notices that 4% of addresses bounce until the provider suspends your account. This lesson covers sending email the way production teams do it: the right provider and protocol, the DNS records that decide whether you reach the inbox, safe templates, background delivery with retries, and the feedback loop that keeps your sender reputation alive.

Transactional and marketing are different jobs

Transactional email is triggered by something the user did and expects: a password reset, a receipt, a "your export is ready" notice. Marketing (or bulk) email is something you decide to send to many people: newsletters, product announcements. The rules differ. Marketing needs consent and an unsubscribe link by law in most places, and mailbox providers judge it harshly. Transactional email must arrive in seconds, every time.

Keep them apart technically too. Send them from different subdomains (for example mail.example.com for transactional and news.example.com for marketing), or through separate streams at your provider. Then a marketing campaign that annoys people cannot drag your password resets into spam.

Do not run your own mail server. A sending service like Amazon SES, Postmark, Resend, SendGrid or Mailgun gives you warmed-up IP addresses with a reputation, bounce and complaint processing, DKIM signing, logs and dashboards. Most cloud providers also block or restrict outbound port 25 on servers by default, precisely because of spam. Your job is choosing a provider, proving you own your domain, and integrating cleanly.

SMTP or an HTTP API

Every provider offers two ways in.

SMTP (smtplib, aiosmtplib)HTTP API (provider SDK or httpx)
PortabilityAny provider, swap by changing host and credentialsProvider-specific code
ErrorsSMTP reply codes, often vagueStructured JSON errors per field
ExtrasHeaders onlyMessage ids, tags, metadata, templates, sometimes idempotency keys
SpeedSeveral round trips per messageOne HTTPS request
Testing locallyPoint at a fake SMTP server like MailpitNeeds a fake or a sandbox mode

For SMTP, connect to port 587 and upgrade with STARTTLS, or to port 465 with TLS from the first byte. Never send credentials over plain port 25. The standard library builds the message, and aiosmtplib sends it without blocking the event loop:

app/email/smtp.py
import aiosmtplib
 
await aiosmtplib.send(
    message,                       # an email.message.EmailMessage
    hostname=settings.smtp_host,
    port=587,
    start_tls=True,
    username=settings.smtp_user,
    password=settings.smtp_password.get_secret_value(),
    timeout=10,
)

An HTTP API call does the same in one request. With SES and boto3 (sync, so run it in a worker or the threadpool):

app/email/ses.py
ses = boto3.client("sesv2")
 
ses.send_email(
    FromEmailAddress="Acme <no-reply@mail.example.com>",
    Destination={"ToAddresses": [to]},
    Content={"Simple": {
        "Subject": {"Data": subject},
        "Body": {"Text": {"Data": text}, "Html": {"Data": html}},
    }},
    ConfigurationSetName="transactional",     # routes bounce and complaint events
)

A good pattern is a small EmailSender protocol in your code with one method, send(message), and an implementation per backend. Your app code never imports a provider SDK directly, tests use a fake, and switching providers is one new class.

SPF, DKIM and DMARC

When Gmail receives a message claiming to be from no-reply@mail.example.com, it asks: did this domain really send it? Three DNS records answer that.

SPF lists the servers allowed to send for a domain. It is checked against the envelope sender (the Return-Path, where bounces go), not the From the user sees:

mail.example.com.  TXT  "v=spf1 include:_spf.your-provider.example -all"

include: pulls in the provider's server list, and -all says everything else fails. SPF allows at most 10 DNS lookups, and every include counts, so a domain that has piled up five providers' includes can quietly start failing.

DKIM puts a cryptographic signature on the headers and body. The provider signs with a private key, and you publish the public key under a selector:

s1._domainkey.mail.example.com.  TXT  "v=DKIM1; k=rsa; p=MIIBIjANBgkqh...IDAQAB"

Many providers ask you to add CNAME records pointing at keys they host instead, so they can rotate keys for you. DKIM survives forwarding, which SPF does not.

DMARC ties them to the address the reader sees. It passes only if SPF or DKIM passes and that passing domain aligns with the From domain. With the default relaxed alignment, mail.example.com aligns with example.com (same organisational domain), but your provider's own bounce domain does not. That is why you set a custom bounce (MAIL FROM) domain or DKIM key on your own domain. DMARC also says what receivers should do with failures and where to send reports:

_dmarc.example.com.  TXT  "v=DMARC1; p=none; rua=mailto:dmarc-reports@example.com"

Start with p=none to collect reports and find every legitimate sender (the billing system, the CRM, the help desk tool), then move to p=quarantine and finally p=reject. Jumping straight to reject silently drops the invoices some forgotten system sends.

Since February 2024, Gmail and Yahoo require more from bulk senders (Gmail defines it as close to 5,000 or more messages a day to its personal accounts): SPF and DKIM, a DMARC record (p=none is enough), alignment, a spam complaint rate kept under 0.3% (aim well below 0.1%), and one-click unsubscribe for marketing mail. Microsoft announced similar rules for Outlook.com from May 2025. Even if you are small today, set all three records up from day one. Check each provider's sender guidelines for the current details.

One-click unsubscribe is RFC 8058: two headers, which must be covered by the DKIM signature. The mailbox provider sends a POST to the URL with the body List-Unsubscribe=One-Click, and you must honour it without asking the user to log in:

List-Unsubscribe: <https://example.com/unsubscribe?t=Zm9vYmFy>, <mailto:unsub@example.com?subject=unsub>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
Match the pairs0/5 matched

Match each record or header to what it does.

Choose an item, then its match on the other side.
Quick check
Your emails pass SPF and DKIM, but DMARC fails. The From is no-reply@example.com, the Return-Path is bounces.provider-mail.net, and DKIM is signed with d=provider-mail.net. Why?
Need a nudge? A hint rules out a wrong answer.

Templates without injection

Build every email with both an HTML part and a plain-text part. Some clients and many spam filters look at the text, and screen readers and smart watches prefer it. Python's EmailMessage does this with set_content for the text and add_alternative for the HTML, which produces a multipart/alternative message:

Pythonbuild_email.py
from email.message import EmailMessagefrom email.utils import make_msgidfrom html import escapefrom urllib.parse import urlencode PUBLIC_BASE_URL = "https://app.example.com" # from settings, never from the request def reset_email(to: str, name: str, token: str) -> EmailMessage: link = f"{PUBLIC_BASE_URL}/reset?{urlencode({'token': token})}" msg = EmailMessage() msg["From"] = "Acme <no-reply@mail.example.com>" msg["To"] = to msg["Subject"] = "Reset your password" msg["Message-ID"] = make_msgid(domain="mail.example.com") msg.set_content(f"Hi {name},\n\nReset your password here (valid 30 minutes):\n{link}\n") msg.add_alternative( f"<p>Hi {escape(name)},</p>" f'<p><a href="{escape(link)}">Reset your password</a> (valid 30 minutes).</p>', subtype="html", ) return msg msg = reset_email("ada@example.org", "<b>Ada</b>", "abc123")print(msg.get_content_type())for part in msg.iter_parts(): print(" ", part.get_content_type())print(msg.get_body(preferencelist=("html",)).get_content().strip()) try: msg.replace_header("Subject", "Hello\r\nBcc: everyone@example.org")except ValueError as e: print("blocked:", e)
Output
Press Run (⌘ Enter) to see what happens.

Three security lessons hide in that block.

Escape user content. A display name of <b>Ada</b> was escaped in the HTML part. In real code, use Jinja2 with autoescape=select_autoescape() so every {{ name }} is escaped by default, and keep HTML and text templates side by side (reset.html, reset.txt).

Build links from configuration. PUBLIC_BASE_URL comes from settings. If you build the reset link from request.base_url or the Host header, an attacker requests a reset for the victim's account while sending Host: evil.example. The victim gets a genuine email from you whose link points at the attacker's site, and clicking it hands over the token. This is host header injection, and it has hit real products.

Headers cannot contain newlines. The modern email package refuses a header with \r\n, which blocks attackers from adding a Bcc: line through a subject field. Older code that glued strings into raw SMTP text did not have this protection.

The HTML itself (tables, inline styles, dark mode, testing across clients) is its own craft, covered in the HTML email lesson of the HTML and CSS track.

Send from a job, not the request

Never call the provider inside the request that triggered the email. The provider adds latency to your response, and when it is down your sign-up endpoint fails even though the user was created. You saw BackgroundTasks in Background Tasks and Async, and it is fine for low-stakes mail, but it runs in the same process: a deploy or crash loses whatever was queued. For email that matters, use a durable queue (Task Queues with Celery) with retries and backoff.

That leaves one more gap, the dual write. If you commit the user and then enqueue the job, a crash in between means no welcome email. If you enqueue first and the commit fails, you email someone who does not exist. The fix is the transactional outbox from Transactions and Concurrency Bugs in Web Apps: write an outbox row in the same transaction as the user, and let a relay worker send what is pending. Combine it with an idempotency key per email (welcome:{user_id}) so a retry after a lost response does not send twice. Some HTTP APIs accept an idempotency key directly; otherwise, check your own table before sending and accept that a rare duplicate is possible.

Pythonemail_outbox.py
import randomimport sqlite3 random.seed(7)db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);CREATE TABLE outbox ( id INTEGER PRIMARY KEY, kind TEXT, recipient TEXT, idempotency_key TEXT UNIQUE, attempts INTEGER DEFAULT 0, status TEXT DEFAULT 'pending');CREATE TABLE suppressed (email TEXT PRIMARY KEY, reason TEXT);INSERT INTO suppressed VALUES ('bounced@example.org', 'hard_bounce');""") def sign_up(email: str) -> None: with db: # one transaction: user row + outbox row cur = db.execute("INSERT INTO users (email) VALUES (?)", (email,)) db.execute("INSERT INTO outbox (kind, recipient, idempotency_key) VALUES (?, ?, ?)", ("welcome", email, f"welcome:{cur.lastrowid}")) class FlakyProvider: """Fails often. Sometimes it sends, then the reply is lost.""" def __init__(self): self.accepted = 0 # calls that reached the provider self.delivered = {} # idempotency key -> recipient def send(self, to: str, key: str) -> None: roll = random.random() if roll < 0.3: raise TimeoutError("timed out before sending") self.accepted += 1 self.delivered.setdefault(key, to) # same key again: no second email if roll < 0.5: raise TimeoutError("sent, but the reply was lost") provider = FlakyProvider() def relay_once(max_attempts: int = 5) -> None: rows = db.execute("SELECT id, recipient, idempotency_key, attempts FROM outbox " "WHERE status = 'pending'").fetchall() for row_id, to, key, attempts in rows: if db.execute("SELECT 1 FROM suppressed WHERE email = ?", (to,)).fetchone(): db.execute("UPDATE outbox SET status = 'suppressed' WHERE id = ?", (row_id,)) continue try: provider.send(to, key) db.execute("UPDATE outbox SET status = 'sent', attempts = ? WHERE id = ?", (attempts + 1, row_id)) except TimeoutError: status = "dead" if attempts + 1 >= max_attempts else "pending" db.execute("UPDATE outbox SET status = ?, attempts = ? WHERE id = ?", (status, attempts + 1, row_id)) db.commit() for email in ["ada@example.org", "linus@example.org", "bounced@example.org", "grace@example.org"]: sign_up(email) for _ in range(5): # a worker polling every few seconds relay_once() for row in db.execute("SELECT recipient, attempts, status FROM outbox"): print(row)print("calls accepted:", provider.accepted, "emails delivered:", len(provider.delivered))
Output
Press Run (⌘ Enter) to see what happens.

Ada's email needed five attempts, and the provider accepted five calls in total, but only three emails went out: the idempotency key turned the "sent, reply lost" retries into no-ops. The bounced address was never attempted. Change the seed and run it again; the delivered count stays at three. In production, a row that reaches dead should raise an alert, not vanish. Also retry only on errors that can succeed later (timeouts, 5xx, 429), and mark a 400 "invalid address" as failed at once.

A welcome email, end to end
APIPostgresWorkerProviderINSERT user + outbox row, COMMITSELECT pending ... FOR UPDATE SKIP LOCKEDsend(key = welcome:42)timeoutsend(key = welcome:42)200, message id m-81fwebhook: delivered / bounced

One transaction. Either both rows exist or neither does, so no email is lost and none is sent for a user who was rolled back.

1/7

Bounces, complaints and suppression

Sending is half the loop. A hard bounce means the address does not exist; a soft bounce is temporary (mailbox full, server busy). A complaint means the recipient pressed "Report spam". Mailbox providers watch your bounce and complaint rates, and so does your provider, which will suspend you if they climb.

Your provider reports these events to a webhook (SES publishes them to SNS or EventBridge; most others POST JSON to your URL). Handle them like any webhook from outside:

  • Verify the signature on the raw body before parsing. Each provider documents its scheme, usually an HMAC over a timestamp and the body.
  • Respond fast with 2xx and do the work in a job, because providers retry slow or failing webhooks.
  • Deduplicate by event id, because they also deliver twice.
  • Suppress: add hard-bounced and complaining addresses to a suppression table and check it before every send, as the outbox block did.
Pythonverify_webhook.py
import hashlibimport hmacimport json SECRET = b"whsec_test_only" def sign(timestamp: int, raw_body: bytes) -> str: return hmac.new(SECRET, f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest() def verify(raw_body: bytes, timestamp: int, signature: str, now: int) -> bool: if abs(now - timestamp) > 300: # older than 5 minutes: maybe a replay return False return hmac.compare_digest(sign(timestamp, raw_body), signature) body = json.dumps({"type": "bounce", "email": "old@example.org", "bounce": "hard"}).encode()sig = sign(1_800_000_000, body) print(verify(body, 1_800_000_000, sig, now=1_800_000_030)) # genuineprint(verify(body.replace(b"hard", b"soft"), 1_800_000_000, sig, now=1_800_000_030)) # tamperedprint(verify(body, 1_800_000_000, sig, now=1_800_009_000)) # replayed later
Output
Press Run (⌘ Enter) to see what happens.

hmac.compare_digest compares in constant time, so an attacker cannot learn the signature byte by byte from response timings. The timestamp window stops someone replaying a captured request next week. In FastAPI, read the body with await request.body() in the webhook route, not a Pydantic model parameter, because you need the exact bytes that were signed.

Predict the outputPython

Add this line to the end of the block above. What does it print?

reparsed = json.dumps(json.loads(body), separators=(",", ":")).encode()
print(verify(reparsed, 1_800_000_000, sig, now=1_800_000_030))
Need a nudge? Hints walk you through it.

Security emails

Password resets and magic links are authentication, so treat them with the same care as passwords.

  • Tokens: generate with secrets.token_urlsafe(32), store only a SHA-256 hash of it with the user id and an expiry (15 to 60 minutes), and mark it used on first use. A database leak then exposes no usable links. Invalidate outstanding tokens when the password changes.
  • No account enumeration: the reset endpoint answers "If an account exists for that address, we have sent a link" whether or not it does. Because sending happens in a job, the response time is the same either way too.
  • Rate limit the reset and magic-link endpoints per address and per IP, which is the next lesson's topic, or someone will use you to flood a victim's inbox.
  • Keep tokens out of logs and referrers: do not log full reset URLs, and set Referrer-Policy: no-referrer on the reset page so the token is not leaked to third-party scripts' servers.
Put it in order5 steps

Put a safe password reset flow in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Local development and tests

Never send real email from a laptop or CI. Mailpit is a fake SMTP server with a web inbox, so you can see exactly what your app sent, HTML and all:

compose.yaml
services:
  mailpit:
    image: axllent/mailpit
    ports:
      - "1025:1025"   # SMTP: point SMTP_HOST/SMTP_PORT here
      - "8025:8025"   # web inbox at http://localhost:8025

In unit tests, replace the sender with an in-memory fake through app.dependency_overrides, then assert on what it captured: the recipient, the subject, and that the link starts with your configured base URL. For the outbox, a test that commits a sign-up and runs the relay once is more valuable than ten tests that mock the provider.

Key terms
transactional email
Email triggered by a user's action, such as a reset or receipt, which must arrive quickly every time.
SPF
A DNS record listing the servers allowed to send mail for the envelope sender domain.
DKIM
A signature over the message, verified with a public key published in DNS under a selector.
DMARC
A DNS policy that requires SPF or DKIM to pass on a domain aligned with the From address, and says what to do with failures.
alignment
The domain that passed SPF or DKIM matches the organisational domain of the visible From address.
suppression list
Addresses you must not send to again, usually after a hard bounce, complaint or unsubscribe.
transactional outbox
Writing the message to send in the same database transaction as the change, then delivering it from a worker.