← Back to blog

Rust Transactional Email API (2026): Send App Mail with an HTTP Client and POST /emails

Send transactional email from Rust with Rovela’s HTTP API: an ordinary ureq or reqwest client, a Bearer key, Idempotency-Key, and documented errors. No official SDK, and not a language-tour rewrite.

Updated November 10, 2026
Rust Transactional Email API (2026): Send App Mail with an HTTP Client and POST /emails

Rust services already speak HTTP; transactional email should too

A Rust service already posts JSON, talks to billing systems, and runs background tasks. The natural way to send transactional email — a “your invoice is ready” note, a usage report, a shipping update, a security alert — is the same pattern: one HTTPS POST with a Bearer key, not an SMTP session hidden behind lettre or a raw SMTP crate.

Rovela’s Email API is built for that. There is no official SDK and no crate you have to treat as first-party. 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).

Rust’s standard library does not include an HTTP client, so this article uses an ordinary crate — ureq in the example, reqwest if you already depend on it. The JSON body and headers are the same either way. This is not a language-tour rewrite; the send email in Rust tour is already published. It is also not an OTP tutorial. Everyday Rust app mail means a small module, environment variables 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 Rust process belongs on POST /emails.

A Rust billing task calls an HTTP client that posts JSON to the email API and receives a message id

What you need before the first Rust send

The first-email guide and the Quick Start are the same five steps, whether your caller is curl or a Rust HTTP crate:

  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 "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. 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).

An ordinary HTTP client, not an official SDK

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. Environment variables read at process start are the right place in a Rust service.

The helper below uses ureq because it is a small blocking client that is easy to call from a worker. If the rest of your crate already uses reqwest, keep that client; only the transport changes. Do not treat either crate as a Rovela SDK.

// src/emails.rs
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::time::Duration;

pub struct Client {
    pub base_url: String,
    pub api_key: String,
    pub from: String,
    agent: ureq::Agent,
}

#[derive(Debug, Deserialize)]
pub struct ApiError {
    #[serde(rename = "statusCode")]
    pub status_code: Option<u16>,
    pub name: Option<String>,
    pub message: Option<String>,
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message.as_deref().unwrap_or("rovela request failed"))
    }
}

impl std::error::Error for ApiError {}

#[derive(Debug, Deserialize)]
pub struct SendResult {
    pub object: String,
    pub id: String,
}

pub struct SendInput<'a> {
    pub to: &'a str,
    pub subject: &'a str,
    pub html: &'a str,
    pub text: &'a str,
    pub reply_to: Option<&'a str>,
    pub tags: Option<serde_json::Value>,
    pub idempotency_key: Option<&'a str>,
}

impl Client {
    pub fn from_env() -> Self {
        let base_url = std::env::var("ROVELA_BASE_URL")
            .unwrap_or_else(|_| "https://api.rovela.dev".into());
        let api_key = std::env::var("ROVELA_API_KEY").expect("ROVELA_API_KEY"); // sending_access
        let from = std::env::var("ROVELA_FROM")
            .unwrap_or_else(|_| "Acme <hello@mail.acme.com>".into());
        let agent = ureq::AgentBuilder::new()
            .timeout(Duration::from_secs(30))
            .build();
        Self { base_url, api_key, from, agent }
    }

    pub fn send(&self, input: SendInput<'_>) -> Result<SendResult, Box<dyn std::error::Error>> {
        let mut payload = json!({
            "from": self.from,
            "to": input.to,
            "subject": input.subject,
            "html": input.html,
            "text": input.text,
        });
        if let Some(reply_to) = input.reply_to {
            payload["reply_to"] = json!(reply_to);
        }
        if let Some(tags) = input.tags {
            payload["tags"] = tags;
        }

        let url = format!("{}/emails", self.base_url.trim_end_matches('/'));
        let mut req = self.agent
            .post(&url)
            .set("Authorization", &format!("Bearer {}", self.api_key))
            .set("Content-Type", "application/json");
        if let Some(key) = input.idempotency_key {
            req = req.set("Idempotency-Key", key);
        }

        let response = req.send_json(payload);
        match response {
            Ok(resp) => Ok(resp.into_json::<SendResult>()?),
            Err(ureq::Error::Status(code, resp)) => {
                let mut err = resp.into_json::<ApiError>().unwrap_or(ApiError {
                    status_code: Some(code as u16),
                    name: None,
                    message: None,
                });
                if err.status_code.is_none() {
                    err.status_code = Some(code as u16);
                }
                Err(Box::new(err))
            }
            Err(e) => Err(Box::new(e)),
        }
    }
}

The documented success body is {"object": "email", "id": "9f1c2e40-..."}. Store that id on the invoice or usage-report job. Do not invent other response fields.

The same request in curl is useful when you are checking the domain and the key before you wire the helper:

curl -X POST https://api.rovela.dev/emails \
  -H "Authorization: Bearer re_your_api_key" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: invoice-ready-inv_2042" \
  -d '{
    "from": "Acme <hello@mail.acme.com>",
    "to": "alice@example.com",
    "subject": "Your invoice is ready",
    "html": "<p>Invoice INV-2042 is ready to download.</p>",
    "text": "Invoice INV-2042 is ready to download."
  }'

A worker that sends after the invoice is stored

Call the helper after the work that matters has already succeeded — the invoice row is persisted, the usage report is in object storage, the shipment is marked dispatched. If the HTTP handler should return quickly, put the send on a queue or a background task and reuse the same Idempotency-Key whenever that job is retried. The header may be up to 256 characters and is remembered for 24 hours (Idempotency-Key).

fn notify_invoice_ready(client: &emails::Client, number: &str, customer_email: &str)
    -> Result<emails::SendResult, Box<dyn std::error::Error>>
{
    let html = format!("<p>Invoice {number} is ready to download.</p>");
    let text = format!("Invoice {number} is ready to download.");
    let key = format!("invoice-ready-{number}");
    client.send(emails::SendInput {
        to: customer_email,
        subject: "Your invoice is ready",
        html: &html,
        text: &text,
        reply_to: Some("billing@mail.acme.com"),
        tags: Some(serde_json::json!({
            "kind": "invoice_ready",
            "invoiceId": number
        })),
        idempotency_key: Some(&key),
    })
}

tags are optional labels returned with the message; they are not a substitute for Idempotency-Key and they are not topic_id. The Email API tags guide covers the documented shapes. reply_to is the right field when a human should be able to answer; see Email API reply-to. Recipients across to, cc, and bcc are capped at 50, and quota is charged per recipient (cc and bcc).

Do not invent 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 helper

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 Rust service:

  • 400 — a missing required field, an unverified or foreign from domain, a template that does not exist, a base64 attachment that does not decode, or more than 50 recipients across to, cc, and bcc.
  • 401 — missing or invalid key, or a sending_access key used to read, reschedule, or cancel a message. Reading events is a full_access (or session) operation.
  • 429 — rate limit exceeded. Each entry in a batch counts individually, so a large batch can trip this partway through.

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 when the credential is valid but lacks permission — for example, a sending_access key used against the Domains API. That is a different failure from a 401. See Email API authentication and the sending domains API guide in this batch.

A Rust SMTP crate over mailbox SMTP is send-as-self and capped; Rust app volume should POST /emails and watch delivery on a webhook

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/:id and GET /emails/:id/events with a full_access key. You are looking for accepted, delivered, or bounced events on that message (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 a Rust handler 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. You can also render HTML in Rust and pass the resulting strings as html and text — that is ordinary Rust, not a Rovela SDK.

What not to do in a Rust codebase

Do not point lettre or another SMTP crate at mx.rovela.dev and send application volume that way. 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 publish a “Rovela SDK” crate that invents endpoints, official clients, numeric HTTP rate (req/s) figures, a sandbox flag, or a dedicated IP. Call the documented HTTP API with an ordinary HTTP crate.

Do not put the key in query parameters, in frontend code, or in a committed file that ships to git. Create a sending_access key for the Rust 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 a detached tokio::spawn as a substitute for idempotency. A background call that retries after a timeout still needs an Idempotency-Key. A background call also does not confirm delivery; only the events API or a webhook does. For retry policy around timeouts and 429s, see Email API retries.

A compact Rust checklist

  1. Verify the sending domain before any production from.
  2. Store a sending_access key in the environment; construct Authorization: Bearer … in server-side code.
  3. Send both html and text. Set reply_to when a human should be able to answer.
  4. Put an Idempotency-Key on any send a queue, payment webhook, or double submit might repeat.
  5. Handle 400, 401, and 429 from the documented error envelope. Remember that 200 means queued.
  6. Store the returned message id on the invoice or usage-report job.
  7. Subscribe to webhooks for delivery, bounces, and complaints; use GET /emails/:id/events only to debug a single message.
  8. Leave mailbox SMTP to people and mail apps.

Once that helper is in place, every other Rust task can call 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 service you already run. For a first request without Rust at all, the curl sending guide and HTTP email API pages are the shortest path.