FastAPI Transactional Email API (2026): Send Mail from a FastAPI Service with POST /emails
How to send transactional email from FastAPI with Rovela’s HTTP Email API: an injectable httpx service, Pydantic settings for the Bearer key, Idempotency-Key, and documented error handling — no official SDK, and not a magic-link tutorial.
Why FastAPI teams want a transactional email API, not a mail server
A FastAPI application already speaks HTTP and JSON. The natural way to send transactional email — an order confirmation, a receipt, a “your invoice is ready” note, a security alert — is the same way: one HTTPS POST with a Bearer key, not an SMTP session stuffed into a worker.
Rovela’s Email API is designed for that pattern. There is no official SDK and no package you have to pin. The base URL is https://api.rovela.dev. You authenticate with Authorization: Bearer re_… (Authentication) and queue a message with POST /emails. The response is a message id. HTTP 200 means the message was accepted and queued, not that it has already arrived (Quick Start).
This is not a redo of a magic-link or OTP tutorial. If you need sign-in links, start from the existing FastAPI magic-link guide and the official verification code example. This article is the everyday FastAPI service: an injectable client, Pydantic settings for the key, an Idempotency-Key on anything a retry might repeat, and documented error handling around the {statusCode, name, message} envelope.
If you are still choosing between HTTP and SMTP, read Email API vs SMTP. Rovela’s SMTP is mailbox SMTP for mail apps (mx.rovela.dev:465, a device credential, send-as-self, 30 messages a minute from one client address). Programmatic volume from a FastAPI process belongs on POST /emails.
What you need before the first FastAPI send
The first-email guide and the Quick Start are the same five steps, whether your caller is curl or FastAPI:
- Create an account. You start on the free plan, which sends real mail. There is no separate sandbox or test key.
- Add and verify a sending domain (a subdomain such as
mail.example.comis a common choice). You cannot send from a domain you have not verified; an unverified or foreignfromis refused with a 400 that names the domain. - Create an API key. A
sending_accesskey can send and nothing else — the right default for production. Afull_accesskey can also read messages and events, and manage domains, templates, and webhooks. The full key is shown once. - Send with
POST /emails. - Confirm delivery in the dashboard, with
GET /emails/:idorGET /emails/:id/events(those reads needfull_accessor a dashboard session), or with a webhook.
from is a string in the documented form "Acme <hello@yourdomain.com>". The address must sit on a verified sending domain. That is the same rule that makes domain email trustworthy: you prove you control the domain before you speak as it.
At least one of html, text, or template is required. Send both html and text where you can — many clients preview the text part (HTML email API).
A small EmailsService for FastAPI
Keep the key on the server. Never put a Rovela key in a browser bundle, a mobile app, or a public repository. A leaked sending_access key can send mail as your domain.
# settings.py
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
rovela_api_key: str
rovela_from: str = "Acme <hello@mail.acme.com>"
rovela_base_url: str = "https://api.rovela.dev"
# emails.py
import httpx
from fastapi import HTTPException
class EmailsService:
def __init__(self, settings):
self.settings = settings
self._client = httpx.AsyncClient(
base_url=settings.rovela_base_url,
headers={
"Authorization": f"Bearer {settings.rovela_api_key}",
"Content-Type": "application/json",
},
timeout=30.0,
)
async def aclose(self) -> None:
await self._client.aclose()
async def send(self, *, to: str, subject: str, html: str, text: str,
idempotency_key: str | None = None,
reply_to: str | None = None) -> dict:
headers = {}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
payload = {
"from": self.settings.rovela_from,
"to": to,
"subject": subject,
"html": html,
"text": text,
}
if reply_to:
payload["reply_to"] = reply_to
resp = await self._client.post("/emails", json=payload, headers=headers)
if resp.status_code == 200:
return resp.json() # {"object": "email", "id": "..."}
try:
err = resp.json()
except ValueError:
err = {"statusCode": resp.status_code, "name": "Error", "message": resp.text}
raise HTTPException(status_code=resp.status_code, detail=err)
Wire the client to the app lifespan so you do not open a new TCP connection on every request:
# main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends, Request
settings = Settings()
@asynccontextmanager
async def lifespan(app: FastAPI):
service = EmailsService(settings)
app.state.emails = service
yield
await service.aclose()
app = FastAPI(lifespan=lifespan)
def emails_service(request: Request) -> EmailsService:
return request.app.state.emails
The curl equivalent of the same send, matching the Emails API and the Quick Start, is:
curl -X POST https://api.rovela.dev/emails \
-H "Authorization: Bearer $ROVELA_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: invoice-10043-ready" \
-d '{
"from": "Acme <hello@mail.acme.com>",
"to": "alice@example.com",
"subject": "Your invoice is ready",
"html": "<p>Invoice 10043 is ready to view.</p>",
"text": "Invoice 10043 is ready to view."
}'
Success looks like {"object": "email", "id": "9f1c2e40-..."}. Store that id next to the invoice or order in your database. You will want it when you debug a single message.
A route that sends after a user action
Transactional mail is triggered by something the user did. A minimal invoice route, with an idempotency key derived from the invoice id so a retried HTTP request does not send two receipts:
@app.post("/invoices/{invoice_id}/email")
async def email_invoice(invoice_id: str, svc: EmailsService = Depends(emails_service)):
invoice = await load_invoice(invoice_id) # your code
result = await svc.send(
to=invoice.customer_email,
subject=f"Your invoice {invoice.number} is ready",
html=f"<p>Invoice {invoice.number} is ready to view.</p>",
text=f"Invoice {invoice.number} is ready to view.",
idempotency_key=f"invoice-{invoice.id}-ready",
reply_to="Acme Billing <billing@acme.com>",
)
return {"email_id": result["id"]}
reply_to is optional and is not a substitute for a verified from. It tells the mail client where a human reply should go (Email API Reply-To). cc and bcc are also documented; they count toward the 50-recipient transport cap and toward monthly quota, because quota is charged per recipient, not per message (Email API CC and BCC).
An Idempotency-Key may be up to 256 characters. A retry of the same request within 24 hours returns the original response instead of sending again. That is the right default for anything driven by a webhook, a queue, or a user double-clicking “send invoice.”
Do not send from the FastAPI process in a way that invents a sandbox. Free-plan keys send real mail. During development, use a verified staging subdomain and recipients you control (how to test a transactional email API).
Errors you should handle in the service
Every error uses the same shape (Quick Start, Email API error handling):
{
"statusCode": 400,
"name": "Bad Request",
"message": "html or text body is required"
}
Documented cases you will actually hit from a FastAPI app:
- 400 — a missing required field, an unverified or foreign
fromdomain, a template that does not exist, a base64 attachment that does not decode, or more than 50 recipients acrossto,cc, andbcc. - 401 — missing or invalid key, or a
sending_accesskey used to read, reschedule, or cancel a message. Reading events is afull_access(or session) operation. - 429 — rate limit or monthly allowance exceeded. Official examples mention
Retry-After. Each entry in a batch counts individually, so a large batch can trip this partway through. Sending also stops for the rest of the calendar month if you exceed the plan allowance (Pricing).
Surface the message field in your own logs as-is. Do not invent a /logs API; delivery history lives in the dashboard and, with a full_access key, on GET /emails/:id and GET /emails/:id/events.
A 403 can appear on management endpoints such as GET /domains when the credential is valid but lacks permission. That is a different failure from a 401, and it is documented on the authentication and first-email pages.
Delivery is asynchronous — do not poll from the request path
A 200 from POST /emails is not a delivery receipt. Confirm later:
- The Emails view in the dashboard.
GET /emails/:idandGET /emails/:id/eventswith afull_accesskey. You are looking foremail.sentfollowed byemail.delivered, oremail.bouncedif the receiving server rejected it (Email delivery status API).- A webhook for anything in production. Verify the HMAC-SHA256 signature (webhook security). Event types include sent, delivered, delayed, bounced, complained, opened, and clicked.
Do not turn your FastAPI route into a polling loop against /emails/:id/events. The docs are explicit: the events endpoint is useful for debugging a single message; systematic handling belongs on a webhook.
POST /emails/batch accepts up to 100 messages, each with the same schema, processed independently. template and topic_id are rejected on the batch endpoint rather than ignored — send those through POST /emails. If you schedule with scheduled_at, reading, rescheduling, and cancelling need full_access or a dashboard session; a sending_access key can only send. The dedicated scheduled email and batch transactional email guides cover those flows in full; this article will not redo them.
Templates are available if you would rather store HTML in Rovela and send { id, variables } (Templates API, templates guide). template is mutually exclusive with html and text.
What not to do in a FastAPI codebase
Do not add an SMTP library and point it at mx.rovela.dev for application volume. That path is for mailboxes and mail apps. A mailbox can send only as its own address, and the documented client limit is 30 messages a minute. You also lose the HTTP API’s tracking, logs, and webhooks (SMTP, Email API vs SMTP relay).
Do not create a “Rovela SDK” wrapper that invents endpoints, official clients, numeric HTTP rate (req/s) figures, a sandbox flag, or a dedicated IP. Call the documented HTTP API.
Do not put the key in query parameters or in frontend code. Create a sending_access key for the FastAPI service. If you send for several customers from one organization, a key can be restricted to a single domain (Authentication, Email API for multi-tenant SaaS).
Do not treat FastAPI BackgroundTasks as a substitute for idempotency. A background task that retries after a timeout still needs an Idempotency-Key. A background task also does not confirm delivery; only the events API or a webhook does.
A compact FastAPI checklist
- Verify the sending domain before any production
from. - Store a
sending_accesskey in environment variables; constructAuthorization: Bearer …on the server. - Reuse one
httpx.AsyncClientfor the process lifetime. - Send both
htmlandtext. Setreply_towhen a human should be able to answer. - Put an
Idempotency-Keyon any send a queue, webhook, or double submit might repeat. - Handle 400, 401, and 429 from the documented error envelope. Remember that 200 means queued.
- Subscribe to webhooks for delivery, bounces, and complaints; use
GET /emails/:id/eventsonly to debug a single message. - Leave mailbox SMTP to people and mail apps.
Once that service is in place, every other FastAPI route can inject it the same way — receipts, security alerts, “your export is ready” notes — without growing a second email stack. That is the point of a transactional email API: one authenticated HTTP call from the application you already run.