Send email with FastAPI
A server-side call to the SendSend API from your FastAPI app.
- Create a test API key in the dashboard first: it never delivers real email. Switch to a live key once your domain is verified.
- Set SENDSEND_API_KEY in the environment that runs the app.
- Add this to
main.py:
import os, uuid, httpx
from fastapi import FastAPI, Response
app = FastAPI()
@app.post("/send")
async def send(to: str):
async with httpx.AsyncClient(timeout=15) as client:
r = await client.post(
"https://api.sendsend.email/v1/emails",
headers={"Authorization": f"Bearer {os.environ['SENDSEND_API_KEY']}", "Idempotency-Key": str(uuid.uuid4())},
json={"from": "Acme <hello@mail.acme.com>", "to": [to], "subject": "Hello from FastAPI", "html": "<p>It works!</p>"},
)
return Response(content=r.content, status_code=r.status_code, media_type="application/json")Good to know
- A
202response means the message was queued, not delivered. See message states and webhooks. - Always send an Idempotency-Key, so a retry cannot send twice.
- Check the response status. Errors have one shape: see Errors.
- More options: attachments, scheduling, headers, templates and React Email.