← Back to blog

Litestar Transactional Email API (2026): Notify That Lab Results Are Ready with POST /emails

Send transactional email from Litestar with Rovela’s HTTP API: a controller or service using httpx, environment variables for the Bearer key, a lab-results-ready notice, and Idempotency-Key. Distinct from the FastAPI, Flask, and Django guides.

Updated November 10, 2026
Litestar Transactional Email API (2026): Notify That Lab Results Are Ready with POST /emails

Litestar already has controllers and dependencies; transactional email belongs in a service, not in a FastAPI clone

A Litestar app is a Python ASGI framework with controllers, dependency injection, and route handlers that run on the server, where a secret can stay secret. Transactional email — “your lab results are ready,” a report that just left review, a link to the result set — is that kind of work. The natural way to send it is one HTTPS POST with a Bearer key from your own service, not an SMTP session, and not a rewrite of a FastAPI, Flask, or Django tutorial with the class names swapped.

Rovela’s Email API is built for that. There is no client library to install and no official Rovela-Litestar plugin in the public docs. Do not look for one in this guide. 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 one-time passcode tutorial, and it is not a contacts, topics, or broadcasts product tour. It is everyday app mail from Litestar server code: a service constructed with httpx, environment variables for the key, a controller that sends after lab results are marked ready, an Idempotency-Key on anything a retry or a double release might repeat, and documented error handling around the {statusCode, name, message} envelope. Nearby Python walkthroughs such as FastAPI, Flask, Django, sending email in Python, and the Python sending guide cover those stacks; this article covers the Litestar shape — a controller, Provide, and httpx.

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 Litestar process belongs on POST /emails.

A Litestar controller depends on an emails service that uses httpx to POST JSON after lab results are ready

What you need before the first Litestar send

The first-email guide and the Quick Start are the same five steps, whether your caller is curl or httpx inside a Litestar service:

  1. Create an account. You start on the free plan, which sends real mail. There is no separate sandbox or test key.
  2. Add and verify a sending domain (a subdomain such as mail.example.com is a common choice). You cannot send from a domain you have not verified; an unverified or foreign from is refused with a 400 that names the domain. See the domain setup guide and what domain email is.
  3. Create an API key. A sending_access key can send and nothing else — the right default for production. A full_access key can also read messages and events, and manage domains, templates, and webhooks. The full key is shown once.
  4. Send with POST /emails.
  5. Confirm delivery in the dashboard, with GET /emails/:id or GET /emails/:id/events (those reads need full_access or a dashboard session), or with a webhook.

from is a string in the documented form "Lab <results@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. How the display name and the address work is covered in the From name guide.

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 service, dependencies, and environment variables

Keep the key on the server. Never put it in a public static directory, never return it from a controller, and never commit it to a repository. A leaked sending_access key can send mail as your domain.

Private values belong in the process environment (or your host’s secret store) and are read with os.environ. A missing key should fail when the service is constructed, not halfway through releasing a result set. Litestar’s Provide is a natural place to construct the service once and inject it into controllers.

# .env (server only; never commit the live key)
ROVELA_API_KEY=re_your_sending_key
ROVELA_FROM=Lab <results@mail.example.com>
# app/emails.py
from __future__ import annotations

import os
from typing import Any

import httpx


class ApiError(Exception):
    def __init__(self, status_code: int, name: str | None, message: str | None) -> None:
        super().__init__(message or f"Rovela: HTTP {status_code}")
        self.status_code = status_code
        self.name = name or "ApiError"
        self.message = message


def require_env(name: str) -> str:
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"Missing required environment variable: {name}")
    return value


class EmailsService:
    def __init__(self, client: httpx.AsyncClient | None = None) -> None:
        self.api_key = require_env("ROVELA_API_KEY")
        self.from_address = require_env("ROVELA_FROM")
        self.client = client or httpx.AsyncClient(timeout=30.0)

    async def send(
        self,
        *,
        to: str | list[str],
        subject: str,
        html: str | None = None,
        text: str | None = None,
        reply_to: str | list[str] | None = None,
        tags: dict[str, str] | None = None,
        idempotency_key: str | None = None,
    ) -> dict[str, Any]:
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }
        if idempotency_key:
            headers["Idempotency-Key"] = idempotency_key

        body: dict[str, Any] = {"from": self.from_address, "to": to, "subject": subject}
        if html:
            body["html"] = html
        if text:
            body["text"] = text
        if reply_to:
            body["reply_to"] = reply_to
        if tags:
            body["tags"] = tags

        response = await self.client.post(
            "https://api.rovela.dev/emails",
            headers=headers,
            json=body,
        )
        payload = {}
        try:
            payload = response.json()
        except ValueError:
            payload = {}
        if response.status_code != 200:
            raise ApiError(
                status_code=int(payload.get("statusCode") or response.status_code),
                name=payload.get("name"),
                message=payload.get("message"),
            )
        return payload

The JSON body and headers are the same ones the Emails API documents. urllib from the standard library also works; this guide uses httpx because async controllers already await. Construct the service from a Litestar dependency, not from a module import that runs at collect time in a worker that does not have the env yet — or make construction lazy, as above, inside __init__ when the app provides the service.

A controller that sends after lab results are ready

A ready result set is a good everyday example because it is not a login code and it is easy to double-send: a clinician clicks Release twice, a reviewer and an automated pipeline both mark the same order ready, or a job is retried. Put the send behind a Litestar controller after you have persisted the release, and give every order a stable Idempotency-Key that includes the order id. 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 (idempotency).

The sketch below is a typical controller with Provide. This is still your code calling POST /emails. It is not a Rovela plugin.

# app/results.py
from litestar import Controller, post
from litestar.di import Provide
from litestar.status_codes import HTTP_200_OK
from pydantic import BaseModel

from app.emails import ApiError, EmailsService


class ReleaseInput(BaseModel):
    patient_email: str
    panel_name: str
    report_url: str


class ReleaseResponse(BaseModel):
    status: str
    email_id: str | None = None
    email_error: str | None = None


def emails_provider() -> EmailsService:
    return EmailsService()


class ResultsController(Controller):
    path = "/results"
    dependencies = {"emails": Provide(emails_provider, sync_to_thread=False)}

    @post("/{order_id:str}/ready", status_code=HTTP_200_OK)
    async def mark_ready(
        self,
        order_id: str,
        data: ReleaseInput,
        emails: EmailsService,
    ) -> ReleaseResponse:
        # Persist the release in your own store, then send.
        # This guide does not invent a Rovela “contacts” or records API.

        try:
            result = await emails.send(
                to=data.patient_email,
                subject="Your lab results are ready",
                html=f"<p>Your <b>{data.panel_name}</b> results are ready.</p><p><a href=\"{data.report_url}\">View report</a></p>",
                text=f"Your {data.panel_name} results are ready: {data.report_url}",
                tags={"purpose": "lab-results-ready", "order_id": order_id},
                idempotency_key=f"lab-results-ready:{order_id}",
            )
            return ReleaseResponse(status="ok", email_id=result["id"])
        except ApiError as err:
            # The release can still stand; mail is queued asynchronously.
            return ReleaseResponse(status="ok", email_error=str(err))
# app/main.py
from litestar import Litestar
from app.results import ResultsController

app = Litestar(route_handlers=[ResultsController])

Do not call the Emails API from a browser form or a public notebook with a shipping key. The Authentication docs are explicit that a client bundle is readable by anyone who has it. Your Litestar process is the right place.

panel_name and report_url are your domain fields. This article does not invent a Rovela lab API — store the order however your app already does, then pass the patient address to POST /emails.

If you later need many personalized messages in one go — a morning release of a batch of panels — use batch (POST /emails/batch, up to 100 messages, each processed independently). template and topic_id are rejected on batch rather than ignored; send those through POST /emails.

Errors you should handle in the service

Every documented error uses the same envelope, so one ApiError covers them (Quick Start, Email API error handling):

{ "statusCode": 400, "name": "Bad Request", "message": "html or text body is required" }

The message says what was wrong. Surface it in your Litestar logs as-is.

  • 400 — a missing required field, a base64 attachment that does not decode, a from domain that does not belong to your organization, a template that does not exist, or more than 50 recipients on one message.
  • 401 — missing or invalid credential, or a sending_access key used to read, reschedule, or cancel a message.
  • 429 — rate limit exceeded. The first-email guide notes that the rate limit is per key, and that each message in a batch counts individually. The official batch example waits on Retry-After when that header is present (and falls back to one second if it is not). This article will not invent a requests-per-second number, because the public docs do not publish one.

HTTP 200 on send is not delivery. If you need to look a message up later, GET /emails/:id and GET /emails/:id/events require a full_access key or a dashboard session — do not put that key in the same service you call from every release. Managing sending domains is a different API and a different key scope (Domains API, Email API authentication, sending domains API). A sending_access key used on a management endpoint such as GET /domains is documented as 403; that is not the same as a failed send.

A controller should not fail the release just because mail queued slowly. Record the ready state, log the error, and let your webhook or a later retry (with the same idempotency key) finish the notice.

Delivery is asynchronous — do not poll from the controller

The controller should record the message id and return. Confirm delivery in the dashboard, with the Email delivery status API, or with a webhook. For production, prefer a webhook over polling GET /emails/:id from the release handler. A ready request should not wait on inbox arrival.

A webhook endpoint in Litestar is another POST handler that reads the raw body, verifies x-resend-signature, and returns 2xx quickly. Verification is byte-exact HMAC-SHA256 over "<timestamp>.<raw body>" (webhook security). A 400 you return because a payload surprised you is a permanent loss; store anything you do not yet understand rather than rejecting it. Deduplicate on the event id. Managing webhook endpoints themselves is covered in the Email Webhooks API guide and the signature verification walkthrough.

When you need a message to go out later — a reminder if the report has not been opened — use scheduled_at (scheduled email). POST /emails/:id/cancel can cancel a message that has not been sent yet; reading, rescheduling, and cancelling need a full_access key or a dashboard session. Public docs do not describe a reschedule request body, so this article will not invent one. When you need many sends in one request, use batch transactional email. Reusable layouts belong in the Templates API and the templates guide.

A FastAPI or Flask handler is a different framework; a Litestar controller posts lab-ready mail to the email API

What not to do in a Litestar codebase

Do not invent a Rovela-Litestar plugin, a dashboard click path that is not in the docs, or a special results object Rovela would have to provide. This integration is plain HTTP from your server code.

Do not paste a FastAPI, Flask, or Django handler into a Litestar file and call it done. Those guides already exist. Litestar’s contract here is a controller, Provide, and httpx.

Do not point smtplib or any other SMTP client at Rovela mailbox SMTP and call that your application mailer. Mailbox SMTP is for mail apps: a mailbox can send only as itself, and a single client address is limited to 30 messages a minute. That is the wrong default for app volume, which is the point of Email API vs SMTP relay as well.

Do not put a Rovela key in a public asset, a notebook, or a repository. Call the API from a service or a job that only runs on the server. Authentication is explicit: a browser bundle is readable by anyone who has it.

Do not treat this guide as a replacement for an OTP article, and do not treat it as a broadcast or contacts tour. Public docs for contacts, topics, segments, and broadcasts are not used as a product walkthrough here. This service is for the mail your lab product sends after a release — results that are ready, a panel that was updated, a notice that a report is available.

Hosted mailboxes are a different product surface. People can read and send from them in a mail app. Your Litestar process should not share a device credential with someone else’s Thunderbird profile.

If you send on behalf of several labs from one organization, restrict a key to a single domain so a leak cannot send as somebody else (Email API for multi-tenant SaaS). Retries of a failed HTTP call should reuse the same idempotency key (Email API retries).

If you later compare providers, the documented pages include Rovela vs Resend, vs SendGrid, vs Postmark, vs Mailgun, vs Brevo, and vs Amazon SES.

A compact Litestar checklist

  • Verify the sending domain before you set from. An unverified domain is a 400, not a silent drop.
  • Keep ROVELA credentials in server environment variables and inject the service into controllers with Provide.
  • Prefer a sending_access key in production release handlers; keep full_access for tooling that reads events or manages webhooks.
  • Send both html and text when you can, and set an Idempotency-Key on any path a retry or a double release can hit twice.
  • Record the message id and return from the controller. Do not fail the release because mail is still queueing. Watch delivery with a webhook, not a loop in the handler.
  • If you need a first request in curl, use the transactional email API overview, the curl sending guide, or the HTTP email API explainer — then come back to this service for the Litestar shape.