Guide · Python
How to send email with FastAPI
Send email from FastAPI with httpx's async client, without blocking the event loop, optionally in a background task.
Last reviewed November 2026
1. Set up
You need a Stack Emails API key (create one free) and a verified sending domain.
pip install fastapi httpx
export STACKEMAILS_API_KEY=se_live_xxxxxxxxxxxx
2. Send your first email
import os
import httpx
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
async def send_welcome(email: str) -> None:
async with httpx.AsyncClient(timeout=10) as client:
res = await client.post(
"https://stackemails.com/v1/emails",
headers={"Authorization": f"Bearer {os.environ['STACKEMAILS_API_KEY']}"},
json={
"from": "Acme <hello@mail.acme.com>",
"to": email,
"subject": "Welcome to Acme",
"html": "<p>Thanks for signing up!</p>",
},
)
res.raise_for_status()
@app.post("/users")
async def create_user(email: str, background: BackgroundTasks):
# ... create the user ...
background.add_task(send_welcome, email)
return {"ok": True}
A successful request returns 202 with the message id, for example { "id": "msg_5b1f0c6c2a8e4e0f", "status": "queued" }. Errors return a JSON body with error.code and error.message (see errors).
Production checklist
- Keep the API key in an environment variable or secret manager, never in client-side code.
- Add an
Idempotency-Keyheader to retries so a timeout never sends twice (idempotency). - Subscribe to webhooks for bounces and complaints.
- Check your domain's SPF, DKIM and DMARC records.
- Start from a tested email template for password resets, receipts and invites.