← Back to blog

SvelteKit Transactional Email API (2026): Send App Mail from Form Actions with POST /emails

Send transactional email from SvelteKit with Rovela’s HTTP API: a server-only module, form actions and +server routes, environment variables for the Bearer key, and Idempotency-Key. Not a magic-link tutorial.

Updated November 10, 2026
SvelteKit Transactional Email API (2026): Send App Mail from Form Actions with POST /emails

SvelteKit already has a server; transactional email belongs there

A SvelteKit app already splits work in two: the browser renders the page, and +page.server.js or a +server route does anything that needs a secret. Transactional email — “your export is ready,” an invoice that can be downloaded, a shipping update, a security notice — is that second kind of work. The natural way to send it is one HTTPS POST with a Bearer key, not an SMTP session hidden in hooks.server.js.

Rovela’s Email API is built for that. There is no official SDK and no SvelteKit adapter 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 passwordless login tutorial. If you need a one-time sign-in link, start from the existing SvelteKit magic link guide. This article is everyday app mail: a server-only module, private environment variables for the key, a form action (or a +server route) that sends after a user action, 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 SvelteKit server belongs on POST /emails.

A SvelteKit form action calls a server-only emails module that posts JSON to the email API and receives a message id

What you need before the first SvelteKit send

The first-email guide and the Quick Start are the same five steps, whether your caller is curl or fetch in a form action:

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

A server-only emails module

Keep the key on the server. Never import it from a +page.js load function that runs in the browser, never put it in PUBLIC_ environment variables, and never ship it in a client bundle. A leaked sending_access key can send mail as your domain. In SvelteKit, $env/static/private (or $env/dynamic/private if the value is supplied at runtime) is the right place.

This helper uses the platform fetch already available in SvelteKit, so the module does not need a second HTTP client just to send mail. The JSON body and headers are the same ones the Emails API documents.

// src/lib/server/emails.js
import { ROVELA_API_KEY, ROVELA_FROM } from '$env/static/private';

const BASE_URL = 'https://api.rovela.dev';

export class ApiError extends Error {
  constructor({ statusCode, name, message }) {
    super(message || `Rovela: HTTP ${statusCode}`);
    this.statusCode = statusCode;
    this.name = name || 'ApiError';
  }
}

export async function sendEmail(
  { to, subject, html, text, replyTo, tags, idempotencyKey },
  fetchImpl = fetch
) {
  const headers = {
    Authorization: `Bearer ${ROVELA_API_KEY}`,
    'Content-Type': 'application/json'
  };
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;

  const body = { from: ROVELA_FROM, to, subject };
  if (html) body.html = html;
  if (text) body.text = text;
  if (replyTo) body.reply_to = replyTo;
  if (tags) body.tags = tags;

  const res = await fetchImpl(`${BASE_URL}/emails`, {
    method: 'POST',
    headers,
    body: JSON.stringify(body)
  });

  const payload = await res.json().catch(() => ({}));
  if (!res.ok) {
    throw new ApiError({
      statusCode: payload.statusCode || res.status,
      name: payload.name,
      message: payload.message
    });
  }
  return payload; // { object: 'email', id: '...' }
}

Store ROVELA_API_KEY and ROVELA_FROM as private environment variables. Do not prefix them with PUBLIC_. 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 a queue, a form re-submit, or a webhook-driven job might retry. A retry of the same request within 24 hours returns the original response instead of sending again (Idempotency-Key). For an export that finished once, a key such as export-ready:{exportId} 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 helper without a sandbox is in how to test a transactional email API.

A form action that sends after a user action

The export-ready example below stays on the server. The form action creates (or looks up) the export, then asks the emails module to notify the user. The browser never sees the key.

// src/routes/exports/+page.server.js
import { fail } from '@sveltejs/kit';
import { sendEmail, ApiError } from '$lib/server/emails';

export const actions = {
  default: async ({ request, locals }) => {
    const data = await request.formData();
    const exportId = String(data.get('exportId') || '');
    if (!exportId) return fail(400, { message: 'Missing export' });

    const exp = await locals.exports.markReady(exportId);
    const downloadUrl = locals.exports.signedUrl(exp);

    try {
      const result = await sendEmail({
        to: exp.userEmail,
        subject: 'Your export is ready',
        html: `<p>Your export can be downloaded here:</p><p><a href="${downloadUrl}">Download</a></p>`,
        text: `Your export can be downloaded: ${downloadUrl}`,
        tags: { purpose: 'export-ready', export_id: exportId },
        idempotencyKey: `export-ready:${exportId}`
      });
      return { ok: true, emailId: result.id };
    } catch (err) {
      if (err instanceof ApiError) {
        return fail(502, { message: err.message, statusCode: err.statusCode });
      }
      throw err;
    }
  }
};

The same helper works from a +server route if the trigger is not a form — a finished background job, a signed internal callback, or another server on your network. Keep that route off the public internet, or authenticate it yourself. The Emails API is called from your server, not from the user’s browser.

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 module

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, 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. Check Retry-After when 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 module you call from every form action. 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 form action

The form action 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 SvelteKit is a POST +server route 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.

Nodemailer or mailbox SMTP in a SvelteKit hooks file is send-as-self and capped; SvelteKit app volume belongs on POST /emails

What not to do in a SvelteKit codebase

Do not point Nodemailer, 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 $env/static/public, a PUBLIC_ variable, or any module imported by a client component. Call the API from +page.server.js, +server routes, or a $lib/server module. Authentication is explicit: a browser bundle is readable by anyone who has it.

Do not treat this guide as a replacement for the magic-link article. Token issuance, single-use redeem, and keeping click tracking off that link are already covered there. This module is for the mail your product sends after a user already has a session — exports, invoices, notices.

Hosted mailboxes are a different product surface. People can read and send from them in a mail app. Your SvelteKit server should not share a device credential with someone else’s Thunderbird 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).

The same module works under SvelteKit’s Node adapter or a serverless adapter, because it is just fetch and private environment variables. What changes is where you trigger it. A form action is the right default for a button the user clicks. A src/routes/api/internal/+server.js route is the right default when a worker in your own network says the export finished. In both cases the emails module stays under $lib/server, and the adapter’s public directory must never receive the key. If you also use hooks.server.js, keep it for authentication and logging — it is a poor place to open an SMTP connection, and it is an easy place to accidentally import a server module into a path that later ships to the client.

A compact SvelteKit checklist

  • Verify the sending domain before you set from. An unverified domain is a 400, not a silent drop.
  • Keep ROVELA_API_KEY in private environment variables and import it only from server modules.
  • Prefer a sending_access key in production form actions; 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 can hit twice.
  • Record the message id and return from the form action. 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 module for the SvelteKit shape.