# Send email from FastAPI

Send from your endpoints with the `mailset` package, and take Mailset’s delivery events on a route of your own. A Pydantic body would break the signature check, so the hook reads `await request.body()`.

## Install the Python SDK

The Python SDK, from pip, uv or Poetry. It brings httpx, the same HTTP client FastAPI’s TestClient is built on.

pip:

```bash
pip install mailset
```

uv:

```bash
uv add mailset
```

poetry:

```bash
poetry add mailset
```

## Send your first email from FastAPI

This is `Mailset`, the blocking client: in a plain `def` endpoint FastAPI runs it in its thread pool. In an `async def` endpoint, use `AsyncMailset` and `await mailset.send(...)`. `"deliver_by": "10m"` and `sent["id"]` work the same way in both.

```python
from mailset import Mailset

# Reads MAILSET_KEY from the environment.
mailset = Mailset()

sent = mailset.send(
    {
        "from": "Acme <hello@example.com>",
        "to": "ana@example.org",
        "subject": "Your Acme code",
        "text": "Your code is 123456.",
        "html": "<p>Your code is <b>123456</b>.</p>",
        "deliver_by": "10m",
    }
)

print(sent["id"], sent["status"])
```

## Verify webhooks in FastAPI

`mailset_events` takes the raw `Request` and reads `await request.body()`, then hands the bytes and `request.headers` to `webhooks.verify` with `MAILSET_HOOK_SECRET`. A failed check raises `MailsetError`, answered 401. Each event is a dict, so a hard bounce is `event["bounce"]["kind"] == "hard"`, and 204 marks the batch kept.

```python
# A FastAPI endpoint for your hook.
import os

from fastapi import FastAPI, Request, Response

from mailset import MailsetError, webhooks

app = FastAPI()
SECRET = os.environ["MAILSET_HOOK_SECRET"]


@app.post("/mailset/events")
async def mailset_events(request: Request) -> Response:
    # The signature covers the body as it came: read
    # its bytes. A pydantic body or request.json()
    # loses what it was made over.
    body = await request.body()
    headers = request.headers
    try:
        events = webhooks.verify(body, headers, SECRET)
    except MailsetError as error:
        return Response(error.code, status_code=401)
    for event in events:
        if event["type"] != "bounced":
            continue
        if event["bounce"]["kind"] == "hard":
            print("Stop writing to", event["recipient"])
    # 2xx once the events are kept. Until then
    # Mailset posts the batch again.
    return Response(status_code=204)
```

In the SDK’s tests: run with FastAPI’s TestClient.

## Send from your own domain

Your product sends as your own domain either way. What changes is where your team’s mail lives.

- **Sending only.** Your team’s mail stays at Google, Microsoft or wherever it is now. Mailset asks for DKIM, a bounce host and DMARC, and leaves your MX alone. [Send from a domain whose mail stays elsewhere](https://mailset.app/docs/recipes/sending-only)
- **Mailboxes too.** Your team’s mail moves to Mailset, with a real mailbox for every address on the domain and your product’s email on the same bill. [Set up a domain](https://mailset.app/guide/onboarding)

```bash
mailset domains add example.com --sending
mailset domains apply example.com --sending
mailset domains check example.com
mailset keys create --send --domain example.com --from hello@example.com --name "Acme API"
```

## What the Python SDK’s build checks

Each line comes from the SDK’s own build, which fails when one stops being true.

- **Python 3.9+**: The oldest its manifest allows (its manifest)
- **Typed throughout**: TypedDicts throughout, checked by mypy (a test)
- **Sync and async**: Mailset and AsyncMailset (a test)

## Where to go from here

- [The Python SDK](https://mailset.app/docs/sdk/python): Every task, from the client’s options to errors and retries.
- [Send email from Python](https://mailset.app/send-email/python): The Python guide, with no framework around it.
- [Webhooks](https://mailset.app/docs/webhooks): The events Mailset posts about your product’s email, and how to check a request’s signature.
- [Give sign-in codes a deadline](https://mailset.app/docs/recipes/deadlines): Use deliverBy so a code that would arrive late is never sent.
- [Retry without sending twice](https://mailset.app/docs/recipes/retries): Make a send safe to repeat with an idempotency key or a Message-ID.
- [Handle bounces](https://mailset.app/docs/recipes/bounces): Tell a dead address from a full inbox, and keep your list clean.
- [Send many messages at once](https://mailset.app/docs/recipes/batches): Up to 100 messages a request, each with its own answer.

## Product email on every plan

Both include 10,000 emails a month, your product’s and your team’s together. Past that it’s $0.40 per 1,000 with pay as you go. Every plan and price: https://mailset.app/pricing

## Sending from FastAPI, asked and answered

### Why not a Pydantic model for the webhook?

FastAPI would parse the JSON before your code runs, and the signature covers the bytes as sent. Take `Request`, read the body, and let `webhooks.verify` return the events.

### Do I need fastapi-mail?

No. fastapi-mail sends through an SMTP server; this package sends through Mailset’s HTTPS API with your key, so `ConnectionConfig` and its SMTP settings go away.

### Can the hook answer first and work later?

Yes, and it should when the work is slow: Mailset gives each post 15 seconds. Keep the events, answer 204, then process them, in a `BackgroundTasks` task for instance.

## Try it on your own domain

7 days free, with everything on. Make a key, run the example above and watch the receipt come back. Start at https://mailset.app/start

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content