Frameworks

How to send email with FastAPI

Short answer

To send email from FastAPI, make an async POST to an email API with httpx, or use the fastapi-mail package to send over SMTP with a ConnectionConfig and MessageSchema. Run the send in BackgroundTasks so the endpoint responds immediately. Keep the key in an environment variable and verify your sending domain with SPF, DKIM and DMARC before going live.

Last checked 16 November 2026

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.
  • SMTPAuthenticationError or a login failure in fastapi-mail: check MAIL_USERNAME and MAIL_PASSWORD. With Mailcandor the username is mailcandor and the password is your API key.
  • TLS errors such as wrong version number: the port and TLS flags do not match. Use MAIL_STARTTLS with 587 and MAIL_SSL_TLS with 465.
  • Validation errors on MAIL_FROM: it must be a bare email address. Put the display name in MAIL_FROM_NAME.
  • An API error object in the logs: read error.message and error.field; a from address 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.

Questions

What is fastapi-mail?

fastapi-mail is a third-party package that sends email over SMTP from FastAPI with async support. You configure it with ConnectionConfig and send MessageSchema objects through a FastMail instance.

Should I send email in a FastAPI background task?

Usually yes. BackgroundTasks runs the send after the response is returned, so the user is not kept waiting. For heavy or critical workloads, use a real job queue that retries.

Can I use requests in FastAPI?

You can, but requests is blocking. In an async endpoint use httpx.AsyncClient, or declare the endpoint with def instead of async def so FastAPI runs it in a thread pool.

How do I set MAIL_STARTTLS and MAIL_SSL_TLS in fastapi-mail?

For port 587, MAIL_STARTTLS=True and MAIL_SSL_TLS=False. For port 465, MAIL_STARTTLS=False and MAIL_SSL_TLS=True. Never turn both on.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.