← All notes

Backend

Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System

OTP emails and welcome emails have different latency requirements. This post covers a dual-path SMTP design where time-sensitive emails send inline with aiosmtplib and background emails queue through Celery with smtplib.

Published
Reading
7 min
Author
Fidelis Uwem Joseph
Series · Part 5 of 9FastAPI in Production
  1. FastAPI Layered Architecture — Routes, Services, and Repositories
  2. Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
  3. Alembic Async Migrations and Idempotent Database Seeding in FastAPI
  4. Stateless OTP Login in FastAPI with JWT and Redis
  5. Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
  6. Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
  7. Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
  8. Mailpit as a Dev SMTP Catch-All Behind Traefik
  9. MinIO as a Self-Hosted S3 Backend in Docker

← Part 4Series overviewPart 6 →

Not every email has the same delivery urgency. An OTP code must arrive before the user loses patience — typically within a few seconds. A welcome email after account creation can arrive a minute later with no consequence. Treating both with the same delivery path means either the welcome email blocks the login response, or the OTP code risks a Celery queue backlog.

This post covers the two-path email system used in production: aiosmtplib for in-request async email when the user is waiting, and smtplib inside Celery workers for background delivery. A single Jinja2 template system serves both paths.

Prerequisites

Python 3.11 with FastAPI, Celery, aiosmtplib, and jinja2 installed. A working Celery worker connected to a Redis broker. For local development, Mailpit provides an SMTP server with a web UI at port 8025.

Background

The async/sync mismatch is the core constraint. FastAPI runs on an async event loop (asyncio). Celery workers run in a standard synchronous Python process. A coroutine like aiosmtplib.send(...) can’t simply be called from a Celery task: tasks are plain functions with no event loop, so calling it just creates a coroutine object that is never awaited, and nothing is sent. Conversely, smtplib.SMTP is blocking and would hold the FastAPI event loop if called from a route handler.

The solution is two sender functions that share the same message composition logic but use different SMTP libraries matched to their execution context.

Implementation

1. Template system

All email templates are Jinja2 HTML files under app/templates/emails/. A single render_template function resolves the template by filename and returns the rendered HTML string:

app/core/email.py
from pathlib import Path
from jinja2 import Environment, FileSystemLoader, select_autoescape
_TEMPLATES_DIR = Path(__file__).parent.parent / "templates" / "emails"
_jinja_env = Environment(
loader=FileSystemLoader(_TEMPLATES_DIR),
autoescape=select_autoescape(["html"]),
)
def render_template(name: str, **context) -> str:
return _jinja_env.get_template(name).render(**context)

autoescape=select_autoescape(["html"]) enables automatic HTML escaping for all .html templates. User-provided values injected into email templates (names, email addresses) are safe by default. Without this, a name like <script>alert(1)</script> renders as JavaScript in the email client.

The _jinja_env is a module-level singleton. Jinja2 caches compiled templates after the first render — reinitialising the environment per request or per task call bypasses that cache.

2. Async path — for OTP and time-sensitive email

The async sender uses aiosmtplib.send() and is called with await directly from FastAPI route handlers or service functions. It runs on the event loop without blocking other requests:

app/core/email.py
import aiosmtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
async def _send(to: str, subject: str, html: str, text: str) -> None:
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = settings.EMAILS_FROM
msg["To"] = to
msg.attach(MIMEText(text, "plain"))
msg.attach(MIMEText(html, "html"))
smtp_kwargs = dict(hostname=settings.SMTP_HOST, port=settings.SMTP_PORT, timeout=10)
if settings.SMTP_USER and settings.SMTP_PASSWORD:
smtp_kwargs["username"] = settings.SMTP_USER
smtp_kwargs["password"] = settings.SMTP_PASSWORD
if settings.SMTP_USE_TLS:
await aiosmtplib.send(msg, start_tls=True, **smtp_kwargs)
else:
await aiosmtplib.send(msg, **smtp_kwargs)

Credentials are only added to smtp_kwargs when both SMTP_USER and SMTP_PASSWORD are non-empty strings. Values read from .env are empty strings, not None, and passing username="" makes aiosmtplib attempt AUTH, which an unauthenticated relay like Mailpit rejects. The timeout matters too: this send happens while the user waits, so a hung SMTP server must fail in seconds, not hold the request open. Together, this makes the same function work against unauthenticated relay servers (like Mailpit in development) and authenticated transactional providers (Postmark, SendGrid) without branching on environment.

3. Synchronous path — for Celery workers

The sync sender mirrors the async version exactly but uses smtplib:

app/core/email.py
import smtplib
import ssl
def _send_sync(to: str, subject: str, html: str, text: str) -> None:
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = settings.EMAILS_FROM
msg["To"] = to
msg.attach(MIMEText(text, "plain"))
msg.attach(MIMEText(html, "html"))
with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT, timeout=30) as smtp:
if settings.SMTP_USE_TLS:
smtp.starttls(context=ssl.create_default_context())
if settings.SMTP_USER and settings.SMTP_PASSWORD:
smtp.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
smtp.send_message(msg)

Pass an explicit SSL context to starttls(). Called without one, smtplib encrypts the connection but does not verify the server’s certificate or hostname, so a man-in-the-middle can present any certificate and read your SMTP password. ssl.create_default_context() turns verification on.

Using a context manager (with smtplib.SMTP(...) as smtp) ensures the connection is closed even if send_message raises. Without it, an exception mid-send leaves a dangling SMTP connection that holds a file descriptor until garbage collection.

4. OTP email — inline async delivery

The OTP sender is a typed wrapper around _send. It renders the template, composes the plain-text fallback, and awaits the send in the request path:

app/core/email.py
async def send_otp_email(to_email: str, code: str) -> None:
try:
html = render_template(
"otp.html",
digits=list(code), # template renders digits as individual boxes
email=to_email,
expires_minutes=10,
year=datetime.now().year,
)
text = (
f"Your login code is: {code}\n\n"
f"This code expires in 10 minutes.\n\n"
"If you didn't request this, ignore this email."
)
await _send(
to=to_email,
subject=f"{code} is your login code",
html=html,
text=text,
)
except Exception as e:
logger.error("Failed to send OTP email to %s: %s", to_email, str(e))
raise

The digits=list(code) line deserves attention. The OTP template renders each digit in a styled individual box. Passing "482916" would require the template to split it with {% for d in code %}. Passing ["4","8","2","9","1","6"] instead moves that logic into Python where it is easy to test, and keeps the template simple.

The error is re-raised after logging. The OTP flow depends on email delivery — a silent failure here means the user gets a verification_token for a code that was never sent.

5. Background email — Celery task

Non-time-sensitive emails — welcome messages, invite notifications — go through the Celery task. The generic task accepts any template name and context dictionary:

app/workers/email_tasks.py
@celery_app.task(
bind=True,
name="email.send",
max_retries=3,
default_retry_delay=30,
acks_late=True,
)
def send_email_task(self, to, subject, template_name, context, text_body=None):
from app.core.email import render_template, _send_sync # local import
try:
html = render_template(template_name, **context)
text = text_body or f"Please view this email in an HTML-capable client."
_send_sync(to=to, subject=subject, html=html, text=text)
return {"sent_to": to, "subject": subject}
except Exception as exc:
logger.error(
"email.send failed (attempt %d/%d): to=%s template=%s error=%s",
self.request.retries + 1, self.max_retries + 1,
to, template_name, exc, exc_info=True,
)
raise self.retry(exc=exc)

render_template and _send_sync are imported inside the task function to break a circular import: app.core.email imports the Celery app to expose the wrappers, and the Celery app autodiscovers this tasks module. Keep local imports for that purpose only. Configuration errors should still fail loudly at worker startup — a worker that starts “healthy” and then fails every task hides the problem until users notice missing emails.

6. Typed convenience wrappers

Each email type gets a typed wrapper that hides the template name and encodes the required context variables:

app/workers/email_tasks.py
def send_welcome_email(to: str, full_name: str) -> None:
send_email_task.delay(
to=to,
subject="Welcome to the platform",
template_name="welcome.html",
context={
"full_name": full_name,
"email": to,
"year": datetime.now().year,
},
text_body=(
f"Hi {full_name},\n\n"
"Your account is ready. Sign in with your email."
),
)
def send_invite_email(to: str) -> None:
send_email_task.delay(
to=to,
subject="You've been added to the platform",
template_name="invite.html",
context={"email": to, "year": datetime.now().year},
text_body=f"You've been invited. Sign in at your email address ({to}).",
)

Callers import send_welcome_email, not send_email_task. Adding a new email type means adding one wrapper function — the template name, subject, and required context variables are documented at the call site.

Testing

Test email delivery locally with Mailpit. It accepts any SMTP connection, never actually delivers, and provides a web UI at http://localhost:8025:

Terminal
$ docker compose -f docker-compose-dev.yml up mailpit -d
# Trigger a welcome email
$ python -c "
from app.workers.email_tasks import send_welcome_email
send_welcome_email(to='alice@example.com', full_name='Alice Mensah')
"
# Open http://localhost:8025 — email should appear within seconds

Confirm SMTP settings are correct before starting the worker:

Terminal
$ python -c "
import smtplib
with smtplib.SMTP('localhost', 1025) as smtp:
print('SMTP connection OK')
"
SMTP connection OK

Verify a background task reaches the worker:

Terminal
$ celery -A app.workers.celery_app worker --loglevel=info &
# In another terminal
$ celery -A app.workers.celery_app call email.send \
--args='["test@example.com","Test Subject","welcome.html",{"full_name":"Test","email":"test@example.com","year":2026},null]'
# Worker output
[INFO] Task email.send[abc...] succeeded in 0.31s: {'sent_to': 'test@example.com', 'subject': 'Test Subject'}

Pitfalls

Production considerations

Mailpit is a development tool — it accepts any credential and never delivers to real addresses. In production, replace it with a transactional provider that supports DKIM signing (Postmark, Resend, SendGrid). Update SMTP_HOST, SMTP_PORT, SMTP_USER, and SMTP_PASSWORD in .env. No code changes required.

For SMTP providers that require TLS on port 587, set SMTP_USE_TLS=true. For providers that use implicit TLS on port 465, aiosmtplib handles this with use_tls=True instead of start_tls=True — update _send() accordingly.

Wrapping up

Time-sensitive email runs inline on the event loop with aiosmtplib. Background email queues through Celery with smtplib. A single Jinja2 environment serves both paths. The typed wrappers mean callers never construct raw context dicts or reference template filenames directly — adding a new email type is a three-step process: template file, wrapper function, call site.

The next problem is delivery monitoring: knowing which emails bounced, which were marked as spam, and which failed to deliver to real addresses. That requires delivery webhooks from your transactional SMTP provider and a table to record delivery state per email attempt.

Going deeper

At-least-once means “sometimes twice”. acks_late=True acknowledges the message only after the task returns. If the worker dies after the SMTP server accepted the message but before the ack, the task runs again and the user gets the email twice. For most emails that is the right trade-off (twice beats never). For emails where it isn’t, pass an idempotency key — a hash of template, recipient and business event — and record it before sending, or use your provider’s idempotency header if it has one.

Retry what is transient, fail what is not. The task above retries every exception. A missing template or a rejected recipient (SMTP 5xx) fails the same way three times, 30 seconds apart. Retry only connection errors and 4xx responses (SMTPServerDisconnected, ConnectionError, SMTPResponseException with a 4xx code), and add retry_backoff=True with jitter so a provider outage doesn’t get a synchronised wave of retries.

Keep personal data out of logs. Logging the full recipient address on every failure puts personal data in your log pipeline. Log a hash or the domain only, and keep the full address in the task’s stored result if support genuinely needs it.

Measure the inline path. The OTP send is on the critical path of login, so track its latency and failure rate as a first-class metric. If the provider’s p99 creeps up, it shows up there first, before anyone reports that codes are slow to arrive.