Email APIs for AI Agents with FastAPI

Build Python API services that send, read, and manage email through MultiMail — with type-safe endpoints and human oversight built in.


FastAPI is a high-performance Python web framework built on type hints and async support. Its automatic validation with Pydantic models pairs well with MultiMail's structured API, making it straightforward to build email-capable backend services for AI agents.

With FastAPI and MultiMail, you can build API services that act as email backends for AI agents. Your FastAPI app handles business logic, orchestrates AI inference, and delegates email operations to MultiMail's API. The default gated_send oversight mode ensures a human approves outgoing emails before delivery.

Whether you are building an AI customer support API, an automated outreach service, or a personal email assistant backend, FastAPI's async capabilities and MultiMail's email infrastructure provide a production-ready foundation.

Built for FastAPI developers

Async-Native

Both FastAPI and MultiMail's API support async operations. Use httpx or aiohttp for non-blocking email API calls that do not block your FastAPI event loop, maintaining high throughput under load.

Pydantic Model Alignment

MultiMail's JSON responses map cleanly to Pydantic models. Define response models for inbox messages, threads, and contacts to get automatic validation, serialization, and OpenAPI documentation.

Dependency Injection for API Keys

FastAPI's dependency injection system cleanly manages MultiMail API credentials. Inject an authenticated HTTP client as a dependency, keeping API key handling centralized and secure.

Background Tasks for Email Processing

Use FastAPI's BackgroundTasks to process emails asynchronously. Check inboxes, generate AI responses, and queue replies without blocking the request-response cycle.

Auto-Generated API Docs

FastAPI auto-generates OpenAPI documentation. Your email endpoints appear in the Swagger UI with full schema details, making it easy for other services and agents to discover and use your email API.


Get started in minutes

MultiMail Client with Dependency Injection
python
import httpx
from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Optional
import os

app = FastAPI(title="Email Agent API")

MULTIMAIL_API = "https://api.multimail.dev/v1"

async def get_multimail_client():
    async with httpx.AsyncClient(
        base_url=MULTIMAIL_API,
        headers={"Authorization": f"Bearer {os.environ[&"cm">#039;MULTIMAIL_API_KEY']}"}
    ) as client:
        yield client


class SendEmailRequest(BaseModel):
    mailbox_id: str
    to: str
    subject: str
    body: str


class EmailMessage(BaseModel):
    id: str
    from_address: str
    subject: str
    body: str
    received_at: str
    thread_id: Optional[str] = None

Create a reusable MultiMail HTTP client as a FastAPI dependency for clean API key management.

Email Send and Inbox Endpoints
python
@app.post("/send")
async def send_email(
    request: SendEmailRequest,
    client: httpx.AsyncClient = Depends(get_multimail_client)
):
    """Send an email. In gated_send mode, queued for human approval."""
    resp = await client.post("/send", json=request.model_dump())
    resp.raise_for_status()
    return resp.json()


@app.get("/inbox/{mailbox_id}")
async def check_inbox(
    mailbox_id: str,
    limit: int = 10,
    client: httpx.AsyncClient = Depends(get_multimail_client)
):
    """Check a mailbox inbox for recent messages."""
    resp = await client.get(
        f"/mailboxes/{mailbox_id}/inbox",
        params={"limit": limit}
    )
    resp.raise_for_status()
    return resp.json()


@app.post("/reply")
async def reply_email(
    message_id: str,
    body: str,
    client: httpx.AsyncClient = Depends(get_multimail_client)
):
    """Reply to an email within its thread."""
    resp = await client.post("/reply", json={
        "message_id": message_id,
        "body": body
    })
    resp.raise_for_status()
    return resp.json()

FastAPI endpoints that proxy email operations through MultiMail with Pydantic validation.

AI-Powered Auto-Reply with Background Tasks
python
from fastapi import BackgroundTasks
from openai import AsyncOpenAI

openai_client = AsyncOpenAI()

async def process_incoming_email(
    message_id: str,
    from_addr: str,
    subject: str,
    body: str,
):
    """Background task: generate an AI reply and queue it via MultiMail."""
    completion = await openai_client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "Draft a brief, professional reply."},
            {"role": "user", "content": f"From: {from_addr}\nSubject: {subject}\n\n{body}"},
        ]
    )
    reply_body = completion.choices[0].message.content

    async with httpx.AsyncClient(
        base_url=MULTIMAIL_API,
        headers={"Authorization": f"Bearer {os.environ[&"cm">#039;MULTIMAIL_API_KEY']}"}
    ) as client:
        await client.post("/reply", json={
            "message_id": message_id,
            "body": reply_body
        })


@app.post("/webhook/email-received")
async def handle_email_webhook(
    payload: dict,
    background_tasks: BackgroundTasks
):
    """Webhook endpoint for MultiMail email.received events."""
    if payload.get("event") == "email.received":
        background_tasks.add_task(
            process_incoming_email,
            payload["message_id"],
            payload["from"],
            payload["subject"],
            payload["body"],
        )
    return {"status": "accepted"}

Process incoming emails in the background using an LLM to generate draft replies.

Thread Retrieval Endpoint
python
@app.get("/threads/{thread_id}")
async def get_thread(
    thread_id: str,
    client: httpx.AsyncClient = Depends(get_multimail_client)
):
    """Get all messages in an email thread."""
    resp = await client.get(f"/threads/{thread_id}")
    resp.raise_for_status()
    return resp.json()


@app.get("/mailboxes")
async def list_mailboxes(
    client: httpx.AsyncClient = Depends(get_multimail_client)
):
    """List all available mailboxes."""
    resp = await client.get("/mailboxes")
    resp.raise_for_status()
    return resp.json()

Retrieve full email thread history for context-aware agent responses.


Step by step

1

Create a MultiMail Account

Sign up at multimail.dev, create a mailbox, and generate an API key.

2

Install Dependencies

Install FastAPI, an async HTTP client, and a server.

bash
pip install fastapi httpx uvicorn
3

Set Your API Key

Store your MultiMail API key as an environment variable.

bash
export MULTIMAIL_API_KEY=mm_live_your_api_key
4

Build Your Endpoints

Create FastAPI routes that call MultiMail's API for email operations. Use Pydantic models for request and response validation.

5

Run and Test

Start your FastAPI server and test endpoints via the auto-generated Swagger UI at /docs.

bash
uvicorn main:app --reload
6

Set Up Webhooks

Configure a MultiMail webhook pointing to your FastAPI server's webhook endpoint for real-time incoming email processing.


Common questions

Should I use httpx or requests for calling the MultiMail API?
Use httpx with its async client. FastAPI is async-native, and using synchronous requests blocks the event loop, reducing throughput. httpx provides the same API as requests but with full async support, making it the right choice for FastAPI applications.
How do I handle MultiMail API errors in FastAPI?
Call resp.raise_for_status() after each API call to convert HTTP errors into exceptions. FastAPI's exception handlers can catch these and return appropriate error responses. You can also define custom exception handlers for specific MultiMail error codes like 429 (rate limit) or 401 (auth failure).
Can I use FastAPI's background tasks for email processing?
Yes. BackgroundTasks run after the response is sent, making them ideal for email processing that does not need to block the request. Use them for AI-powered reply generation, email classification, or batch inbox processing. For heavier workloads, consider Celery or ARQ.
How do I secure my webhook endpoint?
Verify the webhook signature included in the request headers to confirm it came from MultiMail. Additionally, restrict the endpoint to MultiMail's IP ranges and use HTTPS. FastAPI middleware can handle signature verification for all incoming webhook requests.
Can I build a full email client API with FastAPI and MultiMail?
Yes. MultiMail's API covers the full email lifecycle: creating mailboxes, sending and receiving, thread tracking, contact management, and tag organization. Wrap these in FastAPI endpoints with your business logic, authentication, and Pydantic models for a complete email client backend.
How does the oversight mode affect my FastAPI service?
In gated_send mode, the MultiMail send and reply endpoints return a pending status instead of immediate delivery. Your FastAPI service should communicate this to the calling agent or user. You can add an endpoint to check pending email status or set up a webhook to receive approval notifications.

Explore more

The only agent email with a verifiable sender

Email infrastructure built for AI agents. Verifiable identity, graduated oversight, and a 38-tool MCP server. Formally verified in Lean 4.