Skip to content
Browse the docs

Frameworks and agents · Published 2026-09-28 · Updated 2026-11-09 · AgentiSend

Send email from FastAPI

A FastAPI POST route that checks the address, sends with an idempotency key, and returns the message id or the code and fix of a refusal.

To send email from FastAPI, add one POST route that checks the address, calls AgentiSend with an idempotency key derived from the recipient, and returns the message id, or the refusal's code and fix. The app below is that route. It is run by the test suite against a local AgentiSend server's repository, through FastAPI's own TestClient: one send, the same request again replaying it, a malformed address answered before any request is made, and a changed body under the same key refused by the API.

Install

pip install fastapi uvicorn

The agentisend package is standard library only, so pip install agentisend adds no other dependency.

Environment

FastAPI reads none of these itself. The AgentiSend() client reads AGENTISEND_API_KEY (a sending_access key) and AGENTISEND_BASE_URL, and the module reads MAIL_FROM from os.environ when it is imported, so a missing From address stops the app at start rather than at the first send.

The route

"""FastAPI: one POST route that sends a welcome email.

    POST /send  {"email": "ada@example.com", "name": "Ada"}
    200         {"id": "..."}                     accepted
    400         {"error": "..."}                  not one address; the API was not called
    4xx/5xx     {"code": "...", "fix": "..."}     the API refused, and says what to do

Environment: AGENTISEND_API_KEY (a key with sending_access), MAIL_FROM (an
address on a domain you have verified), and optionally AGENTISEND_BASE_URL.
Run: uvicorn app:app
"""

from __future__ import annotations

import os
import re

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel

from agentisend import AgentiSend, AgentiSendError, idempotency_key

agentisend = AgentiSend()  # reads AGENTISEND_API_KEY and AGENTISEND_BASE_URL
MAIL_FROM = os.environ["MAIL_FROM"]

# One address, no spaces, a dot in the domain. The API checks properly; this
# only stops a form typo from costing a request.
ADDRESS = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")

app = FastAPI()


class Signup(BaseModel):
    email: str
    name: str = "there"


@app.post("/send")
def send(signup: Signup) -> JSONResponse:
    email = signup.email.strip()
    if not ADDRESS.match(email):
        return JSONResponse({"error": "email must be one address, like you@example.com"}, status_code=400)

    try:
        sent = agentisend.send_email(
            {
                "from": MAIL_FROM,
                "to": email,
                "subject": "Welcome",
                "text": f"Hi {signup.name}, your account is ready.",
            },
            # Derived from the thing being done, never from the moment: a retry
            # after a timeout replays the first send instead of mailing twice.
            idempotency=idempotency_key("welcome", email),
        )
    except AgentiSendError as err:
        return JSONResponse({"code": err.code, "fix": err.fix}, status_code=err.status)
    return JSONResponse({"id": sent["id"]})
examples/fastapi/app.py, run by the test suite against a local AgentiSend server

The route is a plain def, so FastAPI runs it in its thread pool and the SDK's blocking request never holds up the event loop.

Try it

uvicorn app:app
curl -X POST localhost:8000/send \
  -H 'content-type: application/json' \
  -d '{"email":"you@example.com","name":"Ada"}'

The idempotency key

Every send carries Idempotency-Key: welcome/<address>, derived from what the message is and never from when it was asked for. A client that retries a timed-out request gets the first send's id back instead of mailing the same person twice. The same key with a different body is refused with idempotency_payload_mismatch, which is what the executed run's last request shows: one person, one welcome.

What comes back when it goes wrong

The route answers with the API's status and forwards code and fix, so the caller reads what to do rather than a number. The error catalogue lists every code.

Next

Examples

Prompt for your coding agent

1. Install

npm install agentisend

2. Environment

AGENTISEND_API_KEY
MAIL_FROM
AGENTISEND_BASE_URL=https://api.agentisend.com

3. Send call

"""FastAPI: one POST route that sends a welcome email.

    POST /send  {"email": "ada@example.com", "name": "Ada"}
    200         {"id": "..."}                     accepted
    400         {"error": "..."}                  not one address; the API was not called
    4xx/5xx     {"code": "...", "fix": "..."}     the API refused, and says what to do

Environment: AGENTISEND_API_KEY (a key with sending_access), MAIL_FROM (an
address on a domain you have verified), and optionally AGENTISEND_BASE_URL.
Run: uvicorn app:app
"""

from __future__ import annotations

import os
import re

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel

from agentisend import AgentiSend, AgentiSendError, idempotency_key

agentisend = AgentiSend()  # reads AGENTISEND_API_KEY and AGENTISEND_BASE_URL
MAIL_FROM = os.environ["MAIL_FROM"]

# One address, no spaces, a dot in the domain. The API checks properly; this
# only stops a form typo from costing a request.
ADDRESS = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")

app = FastAPI()


class Signup(BaseModel):
    email: str
    name: str = "there"


@app.post("/send")
def send(signup: Signup) -> JSONResponse:
    email = signup.email.strip()
    if not ADDRESS.match(email):
        return JSONResponse({"error": "email must be one address, like you@example.com"}, status_code=400)

    try:
        sent = agentisend.send_email(
            {
                "from": MAIL_FROM,
                "to": email,
                "subject": "Welcome",
                "text": f"Hi {signup.name}, your account is ready.",
            },
            # Derived from the thing being done, never from the moment: a retry
            # after a timeout replays the first send instead of mailing twice.
            idempotency=idempotency_key("welcome", email),
        )
    except AgentiSendError as err:
        return JSONResponse({"code": err.code, "fix": err.fix}, status_code=err.status)
    return JSONResponse({"id": sent["id"]})

4. Parameter reference

POST /emails
attachments array<object>
bcc any
cc any
expires_at string
from string
headers object
html string
replyTo any
reply_to any
scheduledAt string
scheduled_at string
subject string
tags any
template object
template_id string
template_values object
text string
timezone string
to any required
topicId string
topic_id string
Idempotency-Key header
Resend-Idempotency-Key header

5. Rules

Read the API key on the server. Do not send it to the browser.
Send an Idempotency-Key derived from the thing being done, not from the clock.
A refusal is JSON with code, message, fix and docs_url. Follow fix.

6. Verify

GET /emails/{id}
The id is the one the send call returned.