Fly.io Transactional Email API (2026): Notify That a Preview Environment Is Ready with POST /emails
Send transactional email from an on-demand Fly.io app with Rovela’s HTTP API: a running HTTP handler or a Machine started by a user action, secrets via fly secrets, a “your preview environment is ready” notice, and Idempotency-Key. Not a rewrite of the Fly scheduled Machines guide.
Fly.io can send mail from an on-demand app, not only from a schedule
A Fly.io app that is already running — or a Machine you start because a user just asked for a preview — is a natural place to send transactional email: “your preview environment is ready,” with the URL the reviewer should open. That send is request-driven. It is not a cron, and it is not a rewrite of the Fly scheduled Machines guide, or of Railway cron, Render cron, or a Kubernetes CronJob. Those tutorials already exist. This one is the HTTP handler (or the user-triggered Machine) that fires when the preview actually comes up.
Rovela’s Email API is a single HTTPS call for that work. There is no client library to install and no official Fly.io 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).
Secrets belong in the Machine environment via fly secrets, not in the image and not in a client-side preview banner. Nearby serverless walkthroughs such as AWS Lambda, Azure Functions, Google Cloud Functions, and Netlify Functions cover those hosts; this article covers an on-demand Fly.io app.
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 Fly.io process belongs on POST /emails, which is also the distinction drawn in Email API vs SMTP relay.
What you need before the first Fly.io send
The first-email guide and the Quick Start are the same five steps, whether your caller is curl or fetch inside a Fly.io handler:
- 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. The dashboard asks for four DNS records — SPF, DKIM, DMARC, and return-path. See the domain setup guide and what domain email is. - Create an API key. A
sending_accesskey can send and nothing else — the right default for a production preview notifier. 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 "Previews <previews@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, which is often where a reviewer first sees the preview URL (HTML email API).
Secrets via fly secrets, then a small HTTP helper
Keep the key out of the Docker image and out of fly.toml. Set it on the app (or the Machine) so it is injected as an environment variable at runtime:
# run this from a trusted machine; never commit the live key
fly secrets set ROVELA_API_KEY=re_your_sending_key
fly secrets set ROVELA_FROM='Previews <previews@mail.example.com>'
A leaked sending_access key can send mail as your domain. Do not pass it to a browser preview toolbar, a public status page, or a log line you ship to a third-party frontend. The handler that already decided “this preview is ready” is the right caller.
The helper below is ordinary Node on a Fly.io Machine. The same JSON works from Go, Python, or any other runtime you already run on Fly; this is not an official Fly SDK and not a Rovela library.
// emails.js — runs on the Fly.io Machine, reads process.env
export class ApiError extends Error {
constructor({ statusCode, name, message }) {
super(message || `Rovela: HTTP ${statusCode}`);
this.statusCode = statusCode;
this.name = name || "ApiError";
}
}
function requireEnv(name) {
const value = process.env[name];
if (!value) throw new Error(`Missing required environment variable: ${name}`);
return value;
}
export async function sendEmail(opts) {
const apiKey = requireEnv("ROVELA_API_KEY");
const from = requireEnv("ROVELA_FROM");
const headers = {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
};
if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
const body = { from, to: opts.to, subject: opts.subject };
if (opts.html) body.html = opts.html;
if (opts.text) body.text = opts.text;
if (opts.replyTo) body.reply_to = opts.replyTo;
if (opts.tags) body.tags = opts.tags;
const res = await fetch("https://api.rovela.dev/emails", {
method: "POST",
headers,
body: JSON.stringify(body),
});
const payload = await res.json().catch(() => ({}));
if (!res.ok) {
throw new ApiError({
statusCode: Number(payload.statusCode || res.status),
name: payload.name,
message: payload.message,
});
}
return payload; // { object: "email", id }
}
The JSON body and headers are the same ones the Emails API documents. Import this file only from server modules that run on the Machine.
Notify when a preview environment is ready
A preview URL is easy to announce twice: a health check retries the “ready” callback, a deploy hook and a Machine start hook both fire, or a reviewer clicks “spin up preview” again. Put the send behind your own preview record, and give every environment a stable Idempotency-Key that includes the preview 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 an HTTP handler on an app that is already running, or on a Machine you started because the user asked for a preview — not a fly machines schedule job and not a cron. This article does not invent a Rovela previews API or a Fly marketplace tile.
// previewReady.js — request-driven; not a scheduled Machine
import { ApiError, sendEmail } from "./emails.js";
export async function handlePreviewReady(req, res) {
const body = await readJson(req);
const previewId = String(body.previewId || "");
const reviewerEmail = String(body.reviewerEmail || "");
const previewUrl = String(body.previewUrl || "");
const branch = String(body.branch || "this branch");
if (!previewId || !reviewerEmail || !previewUrl) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "previewId, reviewerEmail, and previewUrl are required" }));
return;
}
// Persist "preview is up" in your own store, then send.
try {
const result = await sendEmail({
to: reviewerEmail,
subject: "Your preview environment is ready",
html: `<p>Your preview environment for <b>${branch}</b> is ready.</p><p>Open it: <a href="${previewUrl}">${previewUrl}</a></p>`,
text: `Your preview environment for ${branch} is ready. Open it: ${previewUrl}`,
tags: { purpose: "preview-ready", preview_id: previewId },
idempotencyKey: `preview-ready:${previewId}`,
});
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ preview: "ready", emailId: result.id }));
} catch (err) {
if (err instanceof ApiError) {
// The preview can still stay up; mail is queued asynchronously.
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ preview: "ready", emailError: err.message }));
return;
}
throw err;
}
}
async function readJson(req) {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
}
previewUrl and branch are your domain fields. Store them however your preview orchestrator already does, then pass the reviewer address and the public URL to POST /emails. If you start a Machine on demand (fly machine start or the Machines API) because a user clicked “open preview,” call this helper from that same request path after the Machine reports healthy — still a user-triggered action, not a schedule.
If a launch later needs many personalized notices in one go — a stack of review apps that all became healthy together — 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. See the batch example and the batch transactional email guide. A reminder that a preview will be stopped later can use scheduled_at (scheduled email), but the “ready” notice itself should stay request-driven.
Errors you should handle in the helper
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 Machine logs as-is.
400— a missing required field, a base64 attachment that does not decode, afromdomain that does not belong to your organization, atemplatethat does not exist, or more than 50 recipients on one message.401— missing or invalid credential, or asending_accesskey 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 onRetry-Afterwhen 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. Retries of a failed HTTP call should reuse the same idempotency key (Email API retries, rate limits).
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 helper you call from every preview. 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 handler should not tear down the preview just because mail queued slowly. Record that the environment is ready, 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 Machine
The handler 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 preview path. A “spin up preview” request should not wait on inbox arrival.
A webhook endpoint on the same Fly.io app is another HTTP 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.
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. Reusable layouts belong in the Templates API and the templates guide.
What not to do on Fly.io
Do not invent a Rovela-Fly plugin, a dashboard click path that is not in the docs, or a special preview object Rovela would have to provide. This integration is plain HTTP from your Machine.
Do not turn this article into a scheduled-Machines rewrite. If the only trigger is a clock, use the scheduled guide. If the trigger is an HTTP request or a Machine started by a user action, stay here.
Do not bake the API key into the image, a public environment page, or a preview banner that the browser can read. Use fly secrets (or an equivalent secret store) and read the value from the process environment on the Machine.
Do not point Nodemailer or any other SMTP client at Rovela mailbox SMTP and call that your preview 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.
Do not treat this guide as a broadcast or contacts tour. Public docs for contacts, topics, segments, and broadcasts are not used as a product walkthrough here. This helper is for the mail your Fly.io app sends when a preview environment becomes ready.
Hosted mailboxes are a different product surface. People can read and send from them in a mail app. Your Fly.io process should not share a device credential with someone else’s Thunderbird profile.
If you send previews on behalf of several tenants from one organization, restrict a key to a single domain so a leak cannot send as somebody else (Email API for multi-tenant SaaS).
If you later compare providers, the documented pages include Rovela vs Amazon SES, vs Mailgun, vs Postmark, vs SendGrid, vs Resend, and vs Brevo.
A compact on-demand Fly.io checklist
- Verify the sending domain before you set
from. An unverified domain is a 400, not a silent drop. - Inject
ROVELAcredentials withfly secretsand import the helper only from request-driven Machine code, not from a scheduled job you confused with this guide. - Prefer a
sending_accesskey in production preview handlers; keepfull_accessfor tooling that reads events or manages webhooks. - Send both
htmlandtextwhen you can, include the public preview URL in both, and set anIdempotency-Keyderived from the preview id. - Record the message
idand return from the handler. Do not stop the preview because mail is still queueing. Watch delivery with a webhook, not a loop in the Machine. - 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 helper for the on-demand Fly.io shape.