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.
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.
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.
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.
Use FastAPI's BackgroundTasks to process emails asynchronously. Check inboxes, generate AI responses, and queue replies without blocking the request-response cycle.
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.
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] = NoneCreate a reusable MultiMail HTTP client as a FastAPI dependency for clean API key management.
@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.
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.
@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.
Sign up at multimail.dev, create a mailbox, and generate an API key.
Install FastAPI, an async HTTP client, and a server.
pip install fastapi httpx uvicornStore your MultiMail API key as an environment variable.
export MULTIMAIL_API_KEY=mm_live_your_api_keyCreate FastAPI routes that call MultiMail's API for email operations. Use Pydantic models for request and response validation.
Start your FastAPI server and test endpoints via the auto-generated Swagger UI at /docs.
uvicorn main:app --reloadConfigure a MultiMail webhook pointing to your FastAPI server's webhook endpoint for real-time incoming email processing.
Email infrastructure built for AI agents. Verifiable identity, graduated oversight, and a 38-tool MCP server. Formally verified in Lean 4.