Phoenix Transactional Email API (2026): Send App Mail from a Context with POST /emails
Send transactional email from Phoenix with Rovela’s HTTP API: a context module that posts JSON with Req, environment configuration for the Bearer key, Idempotency-Key, and documented errors. Not an OTP tutorial and not an Elixir language tour.
Phoenix already talks to other APIs; transactional email is one more
A Phoenix app already calls payment providers from a context, runs Oban or a Task, and keeps secrets in runtime configuration. The natural way to send transactional email — a booking confirmation, an invoice that is ready, a “your export can be downloaded” note, a security alert — is the same pattern: one HTTPS POST with a Bearer key, not an SMTP session hidden behind a Swoosh adapter.
Rovela’s Email API is built for that. There is no official SDK and no Hex package you have to pin to a vendor client. 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 Phoenix OTP tutorial, and it is not an Elixir language-tour rewrite. If you need one-time codes, start from the existing Phoenix OTP guide and the official verification-code example. If you only wanted a first request in Elixir syntax, the send email in Elixir tour is already published. This article is everyday Phoenix app mail: a context module, runtime configuration 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 Phoenix node belongs on POST /emails.
What you need before the first Phoenix send
The first-email guide and the Quick Start are the same five steps, whether your caller is curl or Req:
- 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. 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 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. 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 context module that posts JSON
Keep the key on the server. Never put a Rovela key in a LiveView assign that is serialized to the browser, in a public repo, or in a front-end hook. A leaked sending_access key can send mail as your domain. Runtime configuration (config/runtime.exs reading System.get_env/1) is the right place in a Phoenix release.
This module uses Req, which many Phoenix apps already depend on. If you already use Finch directly, the JSON body and headers are identical — there is still no official SDK.
# lib/acme/emails.ex
defmodule Acme.Emails do
defmodule ApiError do
defexception [:status_code, :error_name, :message]
def message(%__MODULE__{message: msg, status_code: code})
when is_binary(msg) and msg != "",
do: msg
def message(%__MODULE__{status_code: code}), do: "Rovela: HTTP #{code}"
end
def send_email(attrs, opts \\ []) do
key = Application.fetch_env!(:acme, :rovela_api_key)
from = Application.fetch_env!(:acme, :rovela_from)
idempotency_key = Keyword.get(opts, :idempotency_key)
headers =
[{"authorization", "Bearer #{key}"}, {"content-type", "application/json"}]
|> maybe_put_idempotency(idempotency_key)
body =
%{
from: from,
to: attrs[:to],
subject: attrs[:subject],
html: attrs[:html],
text: attrs[:text]
}
|> maybe_put(:reply_to, attrs[:reply_to])
|> maybe_put(:tags, attrs[:tags])
case Req.post("https://api.rovela.dev/emails", json: body, headers: headers, receive_timeout: 15_000) do
{:ok, %Req.Response{status: status, body: payload}} when status in 200..299 ->
{:ok, payload}
{:ok, %Req.Response{status: status, body: payload}} when is_map(payload) ->
{:error,
%ApiError{
status_code: payload["statusCode"] || status,
error_name: payload["name"] || "ApiError",
message: payload["message"] || ""
}}
{:error, reason} ->
{:error, reason}
end
end
defp maybe_put_idempotency(headers, nil), do: headers
defp maybe_put_idempotency(headers, key), do: [{"idempotency-key", key} | headers]
defp maybe_put(map, _key, nil), do: map
defp maybe_put(map, key, value), do: Map.put(map, key, value)
end
Set :rovela_api_key and :rovela_from in runtime config. The from value is the full documented string, including the display name if you use one.
Send an Idempotency-Key header (up to 256 characters) on anything Oban, a retried controller action, or a webhook-driven job might repeat. A retry of the same request within 24 hours returns the original response instead of sending again (Idempotency-Key). For a booking that was confirmed once, a key such as booking-confirmed:{booking_id} is enough.
Optional fields you will actually use: Email API tags come back with the message; reply-to is where replies should go; cc and bcc count as recipients for billing and for the 50-recipient cap. How to exercise the context without a sandbox is in how to test a transactional email API.
A controller (or LiveView) that sends after a booking is confirmed
The booking example stays in the context. The controller confirms the booking, then asks Acme.Emails to notify the guest. LiveView can call the same function from a server event; the socket must never receive the API key.
# lib/acme_web/controllers/booking_controller.ex
def confirm(conn, %{"id" => id}) do
{:ok, booking} = Bookings.confirm(id)
{:ok, result} =
Emails.send_email(
%{
to: booking.guest_email,
subject: "Your booking is confirmed",
html: "<p>Booking #{booking.reference} is confirmed.</p>",
text: "Booking #{booking.reference} is confirmed.",
tags: %{purpose: "booking-confirmed", booking_id: booking.id}
},
idempotency_key: "booking-confirmed:#{booking.id}"
)
conn
|> put_flash(:info, "Booking confirmed")
|> redirect(to: ~p"/bookings/#{booking.id}")
end
If confirmation can be retried (a double submit, an Oban job, a replayed event), the same idempotency key keeps the guest from receiving two confirmations that disagree. Prefer moving the send into a background job if the request also has other work to finish; the context function does not change.
If you later need many personalized messages in one go, 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 context
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 own 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. CheckRetry-Afterwhen it is present. A monthly quota error is also returned as 429; retrying will not create capacity.
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 application env every web node uses to send. Managing sending domains is a different API and a different key scope (Domains API, Email API authentication, sending domains API).
Delivery is asynchronous — do not poll from the request path
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 request path.
A webhook endpoint in Phoenix is a controller 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.
When you need a message to go out later, use scheduled_at (scheduled email). When you need many sends in one request, use batch transactional email. Reusable layouts belong in the Templates API and the templates guide.
What not to do in a Phoenix codebase
Do not point a Swoosh SMTP adapter, Bamboo, or :gen_smtp 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 LiveView assign, a hook, or assets/. Call the API from a context, a worker, or an Oban job. Authentication is explicit: a browser payload is readable by anyone who has it.
Do not treat this guide as a replacement for the OTP article. Code generation, hashed storage, rate limits, and the verification-code example are already covered there. This context is for the mail your product sends after a booking already exists — confirmations, invoices, notices.
Hosted mailboxes are a different product surface. People can read and send from them in a mail app. Your Phoenix node should not share a device credential with someone else’s Apple Mail profile.
If you send on behalf of several customers 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).
Load the key in config/runtime.exs so a release can take ROVELA_API_KEY and ROVELA_FROM from the environment without compiling them into the beam. The context function should return {:ok, payload} or {:error, %ApiError{}} and let the caller decide whether to fail the request or write the error and continue. A LiveView can call that function from a server event after a booking is confirmed, but the socket assigns must not include the key, the request headers, or the raw API response beyond the message id you choose to store. If confirmation is already an Oban job, send from the worker and keep the LiveView to rendering status. The HTTP body does not change. If you also use Plug without LiveView, the same context function is the right call site — keep HTTP concerns in the controller and mail concerns in Acme.Emails.
A compact Phoenix checklist
- Verify the sending domain before you set
from. An unverified domain is a 400, not a silent drop. - Keep the API key in runtime configuration and read it only from server-side modules.
- Prefer a
sending_accesskey in production contexts; keepfull_accessfor tooling that reads events or manages webhooks. - Send both
htmlandtextwhen you can, and set anIdempotency-Keyon any path a retry can hit twice. - Record the message
idand return from the controller or job. Watch delivery with a webhook, not a loop on the request path. - 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 context for the Phoenix shape.