Send with

Send email with FastAPI

FastAPI is async, so use an async HTTP client. httpx works well and can be shared across requests.

Setup

pip install fastapi httpx uvicorn
export ROBUSTEMAIL_API_KEY="rb_test_..."

Send after the response

# main.py
import html
import os
from contextlib import asynccontextmanager

import httpx
from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel

API = "https://robustemail.com/api/v2/emails"
client: httpx.AsyncClient


@asynccontextmanager
async def lifespan(app: FastAPI):
    global client
    client = httpx.AsyncClient(
        timeout=15,
        headers={"Authorization": f"Bearer {os.environ['ROBUSTEMAIL_API_KEY']}"},
    )
    yield
    await client.aclose()


app = FastAPI(lifespan=lifespan)


async def send_email(email: dict, idempotency_key: str | None = None) -> str:
    headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
    res = await client.post(API, json=email, headers=headers)
    body = res.json()
    if res.is_error:
        raise RuntimeError(f"{body['name']}: {body['message']}")
    return body["id"]


class Signup(BaseModel):
    email: str
    name: str


@app.post("/signup", status_code=201)
async def signup(data: Signup, background_tasks: BackgroundTasks):
    user = await create_user(data)  # your own code

    background_tasks.add_task(
        send_email,
        {
            "from": "Acme <hello@acme.com>",
            "to": user.email,
            "subject": "Welcome to Acme",
            "html": f"<p>Hi {html.escape(user.name)}, thanks for signing up.</p>",
        },
        f"welcome-user-{user.id}",
    )
    return {"ok": True}

BackgroundTasks runs after the response is sent, so the sign-up stays fast. One AsyncClient is opened at start-up and reused, which keeps connections warm.

When the email must not be lost

Background tasks run in the same process and are not retried. For receipts and other important email, use a job queue (Celery, arq, Dramatiq) and send with the same idempotency key on every attempt, so a retry never sends twice.

Next