← Back to blog

Deno Fresh Transactional Email API (2026): Acknowledge a Contact Form from a Fresh Route with POST /emails

Send transactional email from a Deno Fresh route handler with Rovela’s HTTP API: Deno.env for the Bearer key, a “we received your contact form” notice, and Idempotency-Key. Plain fetch — not a browser call with a visible key, not an official Deno SDK, and distinct from the Deno runtime tour.

Updated November 10, 2026
Deno Fresh Transactional Email API (2026): Acknowledge a Contact Form from a Fresh Route with POST /emails

Fresh already has a server; transactional email belongs in a route handler, not in an island

A Deno Fresh app can hydrate islands in the browser, but the work that needs a secret still has to run on the server: route handlers under routes/ execute in Deno, where Deno.env can stay private. Transactional email — “we received your contact form,” a note that a human will reply, a copy of the message for your inbox — is that kind of work. The natural way to send it is one HTTPS POST with a Bearer key from your own server code, not an SMTP session, and not a fetch that ships from an island with the key visible in the browser bundle.

Rovela’s Email API is built for that. There is no client library to install and no official Deno or Fresh SDK 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 the Deno runtime tour, and it is not a rewrite of Deno OTP email. Those articles already exist. It is also not a contacts, topics, or broadcasts product tour. It is everyday app mail from a Fresh route: a small emails helper that reads Deno.env (not process.env), a POST handler that sends after a contact form is accepted, an Idempotency-Key on anything a retry or a double click might repeat, and documented error handling around the {statusCode, name, message} envelope. Nearby island and edge walkthroughs such as Hono, Astro, Qwik, Elysia, and Bun cover those stacks; this article covers the Fresh route shape.

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

A Deno Fresh server route acknowledges a contact form, then posts JSON to the email API and receives a message id

What you need before the first Fresh send

The first-email guide and the Quick Start are the same five steps, whether your caller is curl or fetch inside a Fresh handler:

  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. The dashboard asks for four DNS records — SPF, DKIM, DMARC, and return-path. 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 "Studio <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 helper and Deno.env

Keep the key on the server. Never import an emails module into a Fresh island that runs in the browser, never put the key in a public islands/ file, and never return it from a handler the browser can read. A leaked sending_access key can send mail as your domain. Fresh islands are the wrong place for this call, for the same reason a browser fetch is wrong in any other framework.

Private values belong in the process environment (a .env you load only on the server, or your host’s secret store) and are read through Deno.env.get, not Node’s process.env. Fresh is a Deno framework; copying a Node helper unchanged will fail in the place it matters. A missing key should fail when the helper is first used, not halfway through accepting the form.

# .env (server only; never commit the live key)
ROVELA_API_KEY=re_your_sending_key
ROVELA_FROM=Studio <hello@mail.example.com>
// lib/emails.ts — Deno Fresh, Deno.env only
export class ApiError extends Error {
  statusCode: number;
  constructor({ statusCode, name, message }: { statusCode: number; name?: string; message?: string }) {
    super(message || `Rovela: HTTP ${statusCode}`);
    this.statusCode = statusCode;
    this.name = name || "ApiError";
  }
}

function requireEnv(name: string): string {
  const value = Deno.env.get(name);
  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`);
  }
  return value;
}

export async function sendEmail(opts: {
  to: string | string[];
  subject: string;
  html?: string;
  text?: string;
  replyTo?: string | string[];
  tags?: Record<string, string>;
  idempotencyKey?: string;
}) {
  const apiKey = requireEnv("ROVELA_API_KEY");
  const from = requireEnv("ROVELA_FROM");
  const headers: Record<string, string> = {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  };
  if (opts.idempotencyKey) {
    headers["Idempotency-Key"] = opts.idempotencyKey;
  }

  const body: Record<string, unknown> = { 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 as { object: string; id: string };
}

The helper uses the platform fetch already available in Deno, so you do not need a second HTTP client and you do not need an invented official SDK. The JSON body and headers are the same ones the Emails API documents. Import this file only from route modules under routes/, never from islands/.

A Fresh route that sends after a contact form is received

A contact form is a good everyday example because it is not a login code and it is easy to double-send: the visitor double-clicks Submit, a flaky proxy retries the POST, or two tabs submit the same draft. Put the send behind a server-only route handler, and give every submission a stable Idempotency-Key that includes your form id and a submission id you issued. 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 Fresh route at routes/api/contact.ts. The POST handler runs only on the server. The island (or a plain HTML form) posts to this route; it never posts to api.rovela.dev. This is still your code calling POST /emails. It is not a Rovela-Fresh plugin.

// routes/api/contact.ts
import { Handlers } from "$fresh/server.ts";
import { ApiError, sendEmail } from "../../lib/emails.ts";

export const handler: Handlers = {
  async POST(req) {
    const body = await req.json().catch(() => ({}));
    const submissionId = String(body.submissionId || "");
    const visitorEmail = String(body.email || "");
    const visitorName = String(body.name || "there");
    const topic = String(body.topic || "your message");

    if (!submissionId || !visitorEmail) {
      return Response.json(
        { error: "submissionId and email are required" },
        { status: 400 },
      );
    }

    // Persist the submission in your own store, then send.
    // This guide does not invent a Rovela “contacts” or “inbox” API.

    try {
      const result = await sendEmail({
        to: visitorEmail,
        subject: "We received your contact form",
        html: `<p>Hi ${visitorName},</p><p>We received your contact form about <b>${topic}</b> and will reply by email.</p>`,
        text: `Hi ${visitorName}, we received your contact form about ${topic} and will reply by email.`,
        tags: { purpose: "contact-form-received", submission_id: submissionId },
        idempotencyKey: `contact-form:${submissionId}`,
      });
      return Response.json({ accepted: "ok", emailId: result.id });
    } catch (err) {
      if (err instanceof ApiError) {
        // The submission can still stand; mail is queued asynchronously.
        return Response.json({ accepted: "ok", emailError: err.message });
      }
      throw err;
    }
  },
};

A Fresh form page can post JSON or FormData to /api/contact from an island, or you can handle POST on routes/contact.tsx itself and redirect. Either way, the HTTP call to Rovela stays in the server helper. Do not fetch("https://api.rovela.dev/emails") from an island; the Authentication docs are explicit that a browser or app bundle is readable by anyone who has it.

visitorName and topic are your domain fields. This article does not invent a Rovela forms API — store the submission however your app already does, then pass the visitor address to POST /emails.

If you later need many personalized messages in one go — a studio that acknowledges a weekend of inquiries in batches — 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.

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 server 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. 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 form post. 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 route should not fail the submission just because mail queued slowly. Record the form, 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 route

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 contact handler. A form request should not wait on inbox arrival.

A webhook endpoint in Fresh is another server 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 follow-up if nobody on the studio team has replied — 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. Reusable layouts belong in the Templates API and the templates guide.

A browser fetch from a Fresh island leaks the key; a Fresh server route posts to the email API instead

What not to do in a Fresh codebase

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

Do not call the Emails API from a Fresh island, a client useEffect, or any module under islands/. The key would travel with the browser bundle. Call it from a route handler. Do not copy a Node helper that reads process.env and expect it to work unchanged; Fresh runs on Deno, and the documented way to read the secret here is Deno.env.

Do not point an 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 treat this guide as a replacement for the Deno language tour or the Deno 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 helper is for the mail your Fresh product sends after a contact form is received.

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

If you send on behalf of several studios 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 Resend, vs SendGrid, vs Postmark, vs Mailgun, vs Brevo, and vs Amazon SES.

A compact Fresh 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 read them with Deno.env.get. Import the helper only from route handlers, never from islands.
  • Prefer a sending_access key in production form 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 click can hit twice.
  • Record the message id and return from the route. Do not fail the submission 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 helper for the Fresh shape.