Skip to content
DocspackagesDocumentation

@lunora/mail

Transactional email for Lunora — Cloudflare Email Workers or Resend, React templates, queue-backed sends.

PackagesMail

@lunora/mail wraps @visulima/email so you can send transactional email from inside an action. The default transport is Cloudflare Email Workers; Resend is a built-in option, and you can pass any transport you wire yourself. It renders React Email templates inline and can offload delivery to a Cloudflare Queue.

createMailer needs from and a transport: an explicit transport, or else cloudflareSend (the Cloudflare default) or apiKey (Resend). When several are set, the first one in that order wins. Passing none throws, unless you pass a queue: that builds a producer-only mailer whose queue() works and whose send() rejects.

import { createMailer } from "@lunora/mail";

export const mailer = createMailer({
    apiKey: env.RESEND_API_KEY,
    from: "Lunora <noreply@lunora.sh>",
});

Inside a Worker, prefer createMailerFromEnv(env): it reads MAIL_FROM, captures every send into the studio's Mail inbox in a dev environment, and otherwise delivers via cloudflareSend (pass it to send through a SEND_EMAIL binding) or RESEND_API_KEY. The mailer uses cloudflareSend whenever you pass it, so pass it only when the Worker has the binding.

import { createMailerFromEnv } from "@lunora/mail";

const mailer = createMailerFromEnv(env, {
    cloudflareSend: async (from, to, raw) => {
        const { EmailMessage } = await import("cloudflare:email");

        await env.SEND_EMAIL.send(new EmailMessage(from, to, raw));
    },
});

Pass a custom transport to swap providers; pass a Cloudflare queue binding to enable deferred sends via mailer.queue(...).

Sending from an action

import { action, v } from "@/lunora/_generated/server";

import { mailer } from "./mail";

export const welcomeEmail = action.input({ userId: v.id("users") }).action(async ({ ctx, args: { userId } }) => {
    const user = await ctx.runQuery("users:get", { userId });

    await mailer.send({
        to: user.email,
        subject: "Welcome to Lunora",
        html: `<p>Hi ${user.name} — your account is ready.</p>`,
    });
});

Security: recipient policy & HTML content are yours

The mailer blocks header/CRLF/comma injection in addresses, but it does not decide who you send to or what HTML you render:

  • Open relay. Derive to / cc / bcc from server-trusted state (a looked-up user record), never from raw request input, and prefer a fixed or allowlisted from. Sending to an arbitrary user-supplied address turns your deployment into a spam relay.
  • Template XSS / content injection. Treat template HTML like any other HTML sink: never interpolate untrusted data into raw markup without escaping. The mailer sends whatever HTML you hand it verbatim.

React Email templates

Pass a @react-email/components element through the react field. The mailer renders it via renderEmail (a @react-email/render wrapper) and fills in html + text if you didn't provide them yourself:

import Welcome from "../emails/Welcome";

await mailer.send({
    to: user.email,
    subject: "Welcome",
    react: <Welcome name={user.name} />,
});

Queueing

mailer.queue(options) serialises the rendered payload and hands it to the Cloudflare Queue binding you passed as queue. React elements are NOT structured-cloneable, so the queue body always carries pre-rendered html/ text, never the original JSX.

Addresses, the subject and custom headers are validated before the enqueue, with the same checks mailer.send(...) applies — a message with no to recipient is rejected rather than accepted and left to fail on every consumer attempt. An empty cc / bcc array means "no recipients" and is treated exactly like omitting the field.

A consumer Worker re-hydrates the payload and sends it with consumeQueuedSend(mailer, body) — it validates the untrusted message body, then calls mailer.send(...) for you and returns { id }. Call message.ack() after each successful send: Cloudflare Queues are at-least-once, so without a per-message ack a single throw retries the WHOLE batch — resending every already-delivered email in it, not just the one that failed. A failed send is either retryable or a refusal, and the consumer branches on isRetryableMailError(error): a provider outage, rate limit, network failure or any failure the provider did not classify is retried with message.retry() (until the dead-letter queue), while a send the provider refused with an explicit permanent HTTP status (for example a rejected address or message) or a malformed body is acked and logged, because a retry would fail the same way and only fill the dead-letter queue. A send that timed out may already have been accepted, so it fails with isOutcomeUnknownMailError(error) true. Whether it is retried depends on the provider: Resend receives the send's idempotencyKey and drops a repeat, so a timed-out Resend send with a key is retryable and redelivered; through the Cloudflare binding, or without a key, it is not, and the consumer acks and reports it rather than mailing a possible second copy. send() gives the transport 60 seconds by default (sendTimeoutMs on createMailer / createMailerFromEnv, at most 2 147 483 647, setTimeout's limit), and Resend's own 30-second request timeout counts the same way. A 409 from Resend, which means a request under the same key is still being processed, is outcome-unknown too and retried the same way.

Redeliver an outcome-unknown send with a delay (message.retry({ delaySeconds })): the mailer gives up after 60 seconds, but Resend's client can keep the first request going for about two minutes (a 30-second timeout per attempt and up to three retries of a 408, 429 or 503), and a repeat that arrives while it runs is answered with a 409 rather than deduped. Three minutes clears that window. @visulima/email does not pass on Resend's response body, so a 409 for a key reused with a different message (invalid_idempotent_request) looks the same and is retried into the dead-letter queue rather than acked. Build the consumer's mailer with createMailerFromEnv so that in dev the queued message is captured into the studio inbox at consume time instead of delivered:

import { consumeQueuedSend, createMailerFromEnv, isOutcomeUnknownMailError, isRetryableMailError } from "@lunora/mail";

export default {
    queue: async (batch, env) => {
        const mailer = createMailerFromEnv(env);

        for (const message of batch.messages) {
            try {
                // `env.SENT` is a KV namespace: a redelivered key already recorded there is acked without
                // a second send. KV is eventually consistent, so this narrows duplicates, not prevents them.
                await consumeQueuedSend(mailer, message.body, { attempts: message.attempts, enqueuedAt: message.timestamp, sent: env.SENT });
            } catch (error) {
                // Transient, or a send that may have landed with a provider that dedupes on the key (Resend).
                if (isRetryableMailError(error)) {
                    // The first attempt may still be running at the provider (Resend's client keeps a request
                    // going for about two minutes), so give it time: a repeat inside that window is a 409.
                    message.retry(isOutcomeUnknownMailError(error) ? { delaySeconds: 180 } : undefined);
                    continue;
                }

                // A timeout no provider dedupes may have been delivered, so a retry could send a second
                // copy: check the provider's logs. Anything else is a refusal or a malformed body.
                console.error(isOutcomeUnknownMailError(error) ? "mail outcome unknown" : "mail refused", error);
                message.ack();
                continue;
            }
            message.ack();
        }
    },
};

Each queued send carries a stable idempotencyKey — a caller-supplied one (1-256 visible ASCII characters, other than . and ..), or one generated at enqueue time. The ack narrows retries to the message that actually failed, and the key is what lets a redelivery be recognised and skipped. Pass sent — a KV namespace, or anything with KV's get(key) / put(key, value, { expirationTtl }) — and consumeQueuedSend checks it before sending, records the key with the provider's message id after a successful send (for sentTtlSeconds, default one day; KV needs a whole number of at least 60, and anything else fails every message as retryable), and returns { id, deduplicated: true } for a key it has seen. env.SENT exists only once a kv_namespaces entry binds it as SENT in wrangler.jsonc; an unbound one is undefined, which turns dedupe off, so consumeQueuedSend logs a warning when sent is passed as undefined. Only a success is recorded, so a failed attempt never blocks the retry. A store it cannot read, or that does not answer a read within 10 seconds, fails the send as retryable, because nothing has gone out; a store it cannot write after the send, or that does not answer within 10 seconds, is logged and the send still counts as done. With a sent store a body without an idempotencyKey is refused as malformed. Resend also receives the key as its Idempotency-Key request header and drops a repeat within its own 24-hour window; the Cloudflare binding has no such hook. Past that window Resend would deliver the repeat, so pass enqueuedAt: message.timestamp and attempts: message.attempts as above: an outcome-unknown failure of a message enqueued 23 or more hours ago is then not retryable, and a redelivery that old is refused before any request when an earlier delivery may have landed; the consumer acks and reports either. With a sent store that is decided by marks it keeps per delivery, 15 days, under keys no idempotency key can take: sending <n> <key> just before delivery n asks the provider and failed <n> <key> once that send is known not to have gone out. A redelivery is refused while an earlier delivery has sending without failed, so one that failed before reaching the provider (a store outage, say) is still sent; without a store, any redelivery (attempts above 1) counts, since each earlier failure was a send. Without enqueuedAt nothing tracks the message's age, and a send retried for more than a day can be delivered twice.

Upgrading. send() and queue() now validate the key and forward it to Resend. A key must be a string of 1-256 visible ASCII characters (no spaces), and not . or .., which Workers KV refuses as key names; anything else is refused as a non-retryable MailSendError, at enqueue and again in consumeQueuedSend before the sent store is read, so a message an older version enqueued with such a key is acked and logged by the consumer above rather than sent. Drain the queue before deploying if that matters. A key also names one message, not one recipient: Resend never delivers a repeat of a key inside 24 hours (the same message gets the first send's result, a different one a 409 that retries into the dead-letter queue), so a per-user key like verify:${userId} loses the second verification email. Put something unique to the message in the key (a token, a timestamp), or omit it and let queue() mint one.

The store narrows the duplicate window rather than closing it, and nothing on this path can close it. The mark is written after the provider accepted the message, so a crash in between still redelivers and resends, and KV is eventually consistent — a redelivery seconds later can miss a mark that was written. Delivery is at-least-once end to end. If a second copy is unacceptable, claim the key in a strongly-consistent store (a Durable Object, or a D1 row) before the send and release it on failure; that trades a possible duplicate for a possible unsent message, which is the only other side of this coin.

Receiving email

@lunora/mail/inbound is the inbound counterpart: it turns a Cloudflare Email Worker delivery into a call to one of your Lunora functions. The package never imports cloudflare:email: the generated worker entry supplies the real binding, and the package stays unit-testable in plain Node (exactly like the outbound Cloudflare transport).

A Cloudflare Email Worker delivers inbound mail to a top-level email(message, env, ctx) export, a sibling of fetch/scheduled. Export one built by createInboundEmailHandler:

import { authenticatesFrom, createInboundEmailHandler, dispatchToLunoraFunction, parseInboundEmail } from "@lunora/mail/inbound";

export const email = createInboundEmailHandler({
    parse: parseInboundEmail,
    // The sender gate. `authenticatesFrom` accepts only a DMARC/SPF/DKIM pass
    // that is ALIGNED with the `From` domain — see the warning below.
    verify: authenticatesFrom,
    dispatch: dispatchToLunoraFunction({
        shard: env.SHARD,
        functionPath: "inbound:onEmail",
        shardKey: "__root__",
    }),
});

The handler reads message.raw, parses it into a normalised InboundEmail ({ from, to, subject?, messageId?, inReplyTo?, references?, headers, text?, html?, attachments, authentication }, every header CR/LF-checked), and dispatches it. dispatchToLunoraFunction posts an RPC envelope to the root shard stub (the same admin-RPC-over-shard path the dev mail catcher uses), calling the named mutation/action with the parsed message as its args. The RPC is marked a trusted system dispatch — the same marker the scheduler and cron paths set — so the target may be an internalMutation / internalAction. It needs LUNORA_ADMIN_TOKEN to authorize the RPC (read from env by default). When the schema declares .jurisdiction(...), this RPC and the dev capture inbox go to the jurisdiction-pinned shard with no option passed; see Data residency.

A message over maxRawBytes (default 10 MiB, checked against message.rawSize) is refused before it is read: parsing holds the raw bytes, the decoded parts and every attachment at once, and a message near Email Routing's 25 MiB ceiling can outgrow the isolate. It goes down the same path as a parse failure, and so does a message without a numeric rawSize. Upgrading: this limit is new, so mail between 10 and 25 MiB that used to reach dispatch now bounces; raise maxRawBytes (a positive number of bytes) if you accept large attachments and have measured the memory headroom.

Failures split by whether a redelivery could ever succeed. A size, parse or verify failure is permanent — the same bytes fail the same way — so the handler calls message.setReject(reason) and Cloudflare bounces the mail to the sender; override onError to log/forward/swallow instead. A dispatch failure (a shard 502, a briefly-absent LUNORA_ADMIN_TOKEN) is usually transient, but Cloudflare gives an inbound worker no way to say "try later": setReject is a permanent SMTP error and an uncaught throw is permanent too, just opaque (521 Upstream error). There is no inbound redelivery to fall back on. By default the handler therefore bounces with the same fixed generic reason.

To stop a two-second blip losing a legitimate email, absorb the retry inside the worker: pass retain and the handler hands the parsed message to it and accepts the SMTP session, because the message is now owned rather than lost. The sink is yours — a queue, a Durable Object, an alarm:

export const email = createInboundEmailHandler({
    parse: parseInboundEmail,
    dispatch: dispatchToLunoraFunction({ shard: env.SHARD, functionPath: "inbound:onEmail" }),
    retain: async (parsed, { env }) => env.INBOUND_RETRY.send(parsed),
});

If retain itself throws there is nowhere durable to put the message, so it falls back to the generic bounce (the real reason is logged server-side, never reflected to the sender). A dispatch that knows one of its own failures is permanent should call context.message.setReject(...) and return instead of throwing, so it bounces without being queued for a retry that can never succeed.

Inbound mail is untrusted and dispatch is privileged. Cloudflare Email Routing authenticates only the recipient domain, not the sender (email.from and the body are trivially spoofable), and dispatchToLunoraFunction dispatches as a trusted system call, so make the target an internalMutation / internalAction: a public mutation reachable from inbound mail is equally reachable from any browser client, which can post a forged from/to/text straight into your inbox table. The dispatch carries no caller identity, so an rls() policy on the target sees an anonymous caller — it is not bypassed; do the authorization in the handler. Never make a trust decision on email.from. Gate on the DomainKeys Identified Mail (DKIM), Sender Policy Framework (SPF) and Domain-based Message Authentication, Reporting and Conformance (DMARC) verdicts in email.authentication via the verify hook before dispatch, and treat the function input as fully attacker-controlled. A bare pass is not enough: SPF vouches for the envelope MAIL FROM domain and DKIM for the signing d=, both of which the sender picks. authentication.dkim / .spf / .dmarc are lists — one header legitimately reports a method more than once (an ESP-relayed message is DKIM-signed twice) — and each entry carries the domain it is about. Do not hand-roll that check: pass verify: authenticatesFrom and let @lunora/mail answer it. It accepts only when ANY entry has result === "pass" and a domain equal to the From address's domain, treating an entry with a null domain as unauthenticated and an empty list as "not reported" (a DMARC pass already checked alignment). Every copy of this predicate written by hand has been one && away from accepting a genuine spf=pass + dkim=pass for the attacker's OWN domain on a message forging someone else's From.

The receiving function is an ordinary internal mutation/action (the default resolveArgs passes the whole InboundEmail, so declare the fields you use):

import { internalMutation, v } from "@/lunora/_generated/server";

export const onEmail = internalMutation
    .input({
        from: v.string(),
        to: v.array(v.string()),
        subject: v.optional(v.string()),
        text: v.optional(v.string()),
    })
    .mutation(async ({ ctx, args: { from, subject, text } }) => {
        await ctx.db.insert("inbox", { from, subject: subject ?? "", body: text ?? "" });
    });

To reply in the same thread, send with the threading headers built from the parsed message. Both transports pass custom headers through as message headers. The Cloudflare transport writes each header on one unfolded line, so keep References to the newest few ids: a long thread's full chain overruns RFC 5322's 998-character line limit.

const ids = [...(email.references?.split(/\s+/u) ?? []), email.messageId].filter(Boolean);

await mailer.send({
    to: email.from,
    subject: email.subject?.startsWith("Re:") ? email.subject : `Re: ${email.subject ?? ""}`,
    text: "Thanks — we got it.",
    headers: email.messageId ? { "In-Reply-To": email.messageId, References: ids.slice(-10).join(" ") } : undefined,
});

wrangler config

Inbound delivery is configured in Cloudflare, not by codegen. Add an Email Routing rule (dashboard or wrangler) that routes an address to this Worker. If your function replies or forwards, also declare a send_email binding:

{
    "send_email": [{ "name": "OUTBOUND" }],
}

Lunora validates the send_email binding shape but does not manage routing rules; that lifecycle stays in Cloudflare.

Public API

@lunora/mail:

ExportPurpose
createMailer(options)Build a Mailer. Needs from plus one of cloudflareSend / apiKey / transport (or only a queue, for a producer-only mailer)
createMailerFromEnv(env, options?)Build a Mailer from a Worker env: captures in dev, else delivers via Cloudflare/Resend
createCloudflareTransport(options)Cloudflare Email Workers transport (single-recipient; rejects cc/bcc)
createResendTransport(apiKey, from)Resend transport
createCaptureTransport(sink)Dev capture transport: persists to a MailboxSink instead of delivering
createCaptureSink(env, rootShard?)MailboxSink that records into the studio's root-shard inbox
shouldCaptureMail(env)Whether the current env should capture (LUNORA_MAIL_CAPTURE, else dev detection)
renderEmail(element)Render a React Email element to { html, text }
toQueuedPayload(options)Narrow SendOptions to its serializable QueuedSend (drops react)
consumeQueuedSend(mailer, body, options?)Validate a queued payload and mailer.send(...) it, skipping a key already in options.sent (options.enqueuedAt takes message.timestamp, options.attempts takes message.attempts); returns { id, deduplicated }
isRetryableMailError(error)Whether a failed send is worth a redelivery: false for a refusal carrying an explicit permanent HTTP status, for a timed-out send the provider cannot dedupe, and for one consumeQueuedSend was told (enqueuedAt) is 23 or more hours old; true for everything else
isOutcomeUnknownMailError(error)Whether a failed send timed out (or hit Resend's 409 for a key in flight) and may have been delivered; retry it with a delay when it is also retryable, else ack and report it
MailSendErrorThe error a failed send throws; retryable / outcomeUnknown (also on data) carry the decision
Type-onlyMailer, MailTransport, SendOptions, SendPayload, QueueLike, LunoraMailOptions, QueuedSend, SentMailStore, ConsumeQueuedSendOptions, CapturedMail, MailboxSink, CloudflareSend, CloudflareTransportOptions, FromEnvOptions, MailEnv

@lunora/mail/inbound: createInboundEmailHandler(options), dispatchToLunoraFunction(options), parseInboundEmail(raw), authenticatesFrom(email) (the canonical verify gate — true only for a DMARC/SPF/DKIM pass aligned with the From domain), and the inbound types (InboundEmail, InboundAttachment, InboundAuthentication, InboundEmailHandlerOptions, InboundDispatch, InboundVerify, …).

@lunora/mail/testing (dev/test-only): waitForMail(options), listCapturedMail(options), extractLink(mail, { match? }), plus InboxOptions / WaitForMailOptions.

Testing

For a unit test, build a stub transport ({ send: async () => ({ id: "stub" }) } is enough) and pass it as transport. It needs no network and no API keys.

For end-to-end flows that depend on email (sign-up verification, forgot-password, magic links), @lunora/mail/testing reads the dev capture inbox over the admin RPC so a test can drive "request reset → read the email → follow the link" deterministically. It needs the app's base URL and the admin token (LUNORA_ADMIN_TOKEN):

import { extractLink, waitForMail } from "@lunora/mail/testing";

const mail = await waitForMail({
    baseUrl: "http://localhost:8787",
    adminToken: process.env.LUNORA_ADMIN_TOKEN!,
    to: "alice@example.com",
    subjectMatch: "Reset your password",
});

const link = extractLink(mail, { match: "/reset-password" });