FastAPI has no built-in email support, but it is a good fit for both common approaches. For an email API, make an async request with httpx. For SMTP, the fastapi-mail package wraps an async SMTP client. In either case, use BackgroundTasks so the endpoint returns before the email is sent.
Option 1: an email API with httpx
pip install fastapi httpx
Share one httpx.AsyncClient across requests by creating it in the app’s lifespan. Reusing the client keeps connections open between emails.
# main.py
import os
from contextlib import asynccontextmanager
import httpx
from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel, EmailStr
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.mail = httpx.AsyncClient(
base_url="https://api.mailcandor.com/v1",
headers={"Authorization": f"Bearer {os.environ['MAILCANDOR_KEY']}"},
timeout=10,
)
yield
await app.state.mail.aclose()
app = FastAPI(lifespan=lifespan)
async def send_email(client: httpx.AsyncClient, payload: dict, key: str | None = None):
headers = {"Idempotency-Key": key} if key else {}
resp = await client.post("/emails", json=payload, headers=headers)
if resp.status_code != 202:
error = resp.json()["error"]
raise RuntimeError(f"{error['type']}: {error['message']}")
return resp.json()["id"]
class Signup(BaseModel):
email: EmailStr
name: str
@app.post("/signup", status_code=201)
async def signup(body: Signup, background_tasks: BackgroundTasks):
# ... create the user ...
background_tasks.add_task(
send_email,
app.state.mail,
{
"from": "Acme <hello@acme.com>",
"to": body.email,
"subject": "Welcome to Acme",
"text": f"Hi {body.name}, thanks for signing up.",
},
f"welcome-{body.email}",
)
return {"ok": True}
EmailStr needs the email-validator package (pip install "pydantic[email]"). The base_url ends in /v1, so the relative path /emails resolves to https://api.mailcandor.com/v1/emails.
The API responds with 202 and an id when the email is queued. Deliveries and bounces arrive later as webhooks, which you can receive with another FastAPI route.
Why idempotency keys matter here
Background tasks do not retry on their own. If you add a retry around send_email (for example with the tenacity package), the Idempotency-Key header makes it safe: a repeat with the same key returns the first response instead of sending a second email.
Option 2: fastapi-mail over SMTP
pip install fastapi-mail
# mail.py
import os
from fastapi_mail import ConnectionConfig, FastMail, MessageSchema, MessageType
conf = ConnectionConfig(
MAIL_USERNAME="mailcandor",
MAIL_PASSWORD=os.environ["MAILCANDOR_KEY"],
MAIL_FROM="hello@acme.com",
MAIL_FROM_NAME="Acme",
MAIL_SERVER="smtp.mailcandor.com",
MAIL_PORT=587,
MAIL_STARTTLS=True,
MAIL_SSL_TLS=False,
USE_CREDENTIALS=True,
VALIDATE_CERTS=True,
)
fm = FastMail(conf)
# main.py
from fastapi import BackgroundTasks, FastAPI
from fastapi_mail import MessageSchema, MessageType
from pydantic import BaseModel, EmailStr
from .mail import fm
app = FastAPI()
class Invite(BaseModel):
email: EmailStr
@app.post("/invite")
async def invite(body: Invite, background_tasks: BackgroundTasks):
message = MessageSchema(
subject="You have been invited to Acme",
recipients=[body.email],
body="<p>Click <a href=\"https://acme.com/join\">here</a> to join.</p>",
subtype=MessageType.html,
)
background_tasks.add_task(fm.send_message, message)
return {"ok": True}
For port 465, set MAIL_PORT=465, MAIL_STARTTLS=False and MAIL_SSL_TLS=True. The SMTP ports guide explains why there are two.
fastapi-mail can also render Jinja2 templates: set TEMPLATE_FOLDER in the config and pass template_name to send_message. In tests, SUPPRESS_SEND=1 stops it from connecting to the server.
Background tasks vs a job queue
BackgroundTasks runs in the same process after the response is sent. That is ideal for a welcome or invite email. It has limits:
- If the process restarts, queued tasks are lost.
- Failures are only logged; nothing retries.
- Heavy work still competes with your request handling.
For receipts, password resets or anything you must not lose, use a job queue (Celery, ARQ, Dramatiq) with retries. With the API option, combine retries with an idempotency key so a retry never sends twice.
Avoid blocking calls
Inside async def endpoints, do not use requests or smtplib directly: they block the event loop and stall every other request on that worker. Use httpx.AsyncClient or fastapi-mail, which are async, or define the endpoint with plain def so FastAPI runs it in a thread pool.
Rendering HTML templates
For the API option, render templates yourself with Jinja2, the same engine FastAPI uses for HTML responses. Create one Environment(loader=FileSystemLoader("templates/emails"), autoescape=True) at startup and call env.get_template("welcome.html").render(name=body.name) to fill the html field. Autoescaping keeps user input from injecting markup into your emails.
Common problems
- The endpoint is slow even with BackgroundTasks: the background task runs after the response in the same worker. If it uses blocking code, it still holds up that worker. Check that the send is truly async.
SMTPAuthenticationErroror a login failure in fastapi-mail: checkMAIL_USERNAMEandMAIL_PASSWORD. With Mailcandor the username ismailcandorand the password is your API key.- TLS errors such as wrong version number: the port and TLS flags do not match. Use
MAIL_STARTTLSwith 587 andMAIL_SSL_TLSwith 465. - Validation errors on
MAIL_FROM: it must be a bare email address. Put the display name inMAIL_FROM_NAME. - An API error object in the logs: read
error.messageanderror.field; afromaddress on an unverified domain is a common cause.
Log failures from background tasks yourself. FastAPI does not report them to the client, because the response has already been sent.
Which should you choose?
| Email API (httpx) | fastapi-mail (SMTP) | |
|---|---|---|
| Packages | httpx | fastapi-mail |
| Async | Yes | Yes |
| Safe retries | Idempotency keys | Not built in |
| Delivery events | Webhooks per email id | Usually none |
| Templates | Render with Jinja2 yourself | Built-in Jinja2 support |
Both use the same Mailcandor key. If you are not tied to SMTP, the email API is less to configure. For plain Python without a framework, see the Python email guide.
Before you send: verify your domain
The domain in MAIL_FROM or your from field needs SPF, DKIM and DMARC records, or receiving servers will send your mail to spam. Add the domain with your provider and publish the records it gives you; the SPF, DKIM and DMARC guide walks through each one.