Menu

Sending email from FastAPI: SMTP, Resend, templates and testing
📰

Sending email from FastAPI: SMTP, Resend, templates and testing

DEV Community: fastapi·patrykkomow12·3 days ago
#8aA1Ybjn
#devtofastapi#devto#dev#email#html
Reading 0:00
15s threshold

Every SaaS sends the same handful of emails: confirm your address, reset your password, your payment failed. Here is a small module that sends them over SMTP or an HTTP API, in HTML and plain text, in the user's language, without blocking the event loop, and without an email outage taking your sign-up form down with it.

One function, and it never raises

The rest of the app calls one function, with the name of an email and its parameters:

await send_template ( user . email , "verify" , user . locale , link = link , hours = 48 )

Enter fullscreen mode

Exit fullscreen mode

Underneath, a small dataclass and a dispatcher:

# app/email/__init__.py @dataclass class Email : to : str subject : str text : str html : str | None = None

# Filled by the "memory" backend. Tests read and clear it. outbox : list [ Email ] = [ ]

async def send_email ( to : str , subject : str , text : str , html : str | None = None ) -> bool : """Sends one email.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.