skip to content

In a Cloudflare Email Worker, what do message.forward(), message.setReject() and message.reply() each do inside the email() handler?

level: middleimportance: should knowfreq 30%

answer

  1. ForwardableEmailMessage in email()
  2. forward: verified address, X- headers
  3. setReject: permanent SMTP error
  4. reply: once, to the sender
  5. EmailMessage from cloudflare:email

basics

~20 s

An Email Worker's email(message, env, ctx) handler gets the incoming message. message.forward() relays it to a verified destination, message.setReject() sends a permanent SMTP error back to the sending server, and message.reply() sends one threaded reply to the original sender.

solid answer

~50 s

When a routing rule's action is *Send to a Worker*, Email Routing calls the Worker's `email(message, env, ctx)` handler with a `ForwardableEmailMessage`. It carries the envelope `from` and `to`, the `headers`, a `raw` stream of the MIME message and its `rawSize`. `message.forward(rcptTo, headers?)` relays the message to a verified destination address of the account. It may be called more than once, but its `Headers` argument can add only `X-` headers. `message.setReject(reason)` returns nothing; Email Routing answers the sending server with a permanent SMTP error that carries the reason. `message.reply()` takes an `EmailMessage` from `cloudflare:email`, built from raw MIME. It throws unless the incoming mail has a valid DMARC result, the reply goes to the original sender from the receiving domain, it is the only reply in this event, and the `References` header has no more than 100 entries.

code

javascript · 37 lines
javascript
import { EmailMessage } from "cloudflare:email";

const STAFF = {
  "[email protected]": ["[email protected]", "[email protected]"],
  "[email protected]": ["[email protected]"],
};

export default {
  async email(message, env, ctx) {
    // Drop any +detail so support+web@ still finds support@.
    const to = message.to.toLowerCase().replace(/\+[^@]*@/, "@");
    const inboxes = STAFF[to];
    if (!inboxes) {
      message.setReject("No such mailbox");
      return;
    }

    const tag = new Headers({ "X-Routed-By": "email-worker" });
    await Promise.all(inboxes.map((addr) => message.forward(addr, tag)));

    const original = message.headers.get("message-id");
    if (to === "[email protected]" && original) {
      const raw = [
        `From: ${message.to}`,
        `To: ${message.from}`,
        `Subject: Re: ${message.headers.get("subject") ?? ""}`,
        `In-Reply-To: ${original}`,
        `References: ${original}`,
        `Message-ID: <${crypto.randomUUID()}@shop.example>`,
        "Content-Type: text/plain; charset=utf-8",
        "",
        "Thanks, we have your request and will answer within one business day.",
      ].join("\r\n");
      await message.reply(new EmailMessage(message.to, message.from, raw));
    }
  },
};

go deeper

for a junior

Recall the handler signature email(message, env, ctx) and the three actions: forward to a verified address, reject with a reason, reply to the sender.

for a middle

Explain the message's members, why forward() needs a verified destination and adds only X- headers, how setReject() differs from Drop, and each condition under which reply() throws.

for a senior

Show you guard the failure paths: catch a forward() that fails on unauthenticated mail, never let a failed reply block the forward, and keep heavy parsing within the Workers CPU limits on the plan in use.

for a principal

Weigh which outcome each address should give senders: a visible rejection, a silent drop or an automatic reply, and who approves auto-replies that speak for the company.

## The email() handler and its message An **Email Worker** is an ordinary Cloudflare Worker that exports an `email()` handler beside, or instead of, `fetch()`. Email Routing calls it when a routing rule (or the catch-all rule) has the action *Send to a Worker*. The handler receives three arguments: the message, the `env` bindings and the `ctx` execution context. The message is a `ForwardableEmailMessage`: | Member | What it is | |---|---| | `message.from` | the envelope sender (SMTP `MAIL FROM`) | | `message.to` | the envelope recipient (SMTP `RCPT TO`), with any `+detail` kept | | `message.headers` | a `Headers` object: `subject`, `message-id`, `from` and the rest | | `message.raw` | a `ReadableStream` of the whole MIME message | | `message.rawSize` | its size in bytes | To read the body or the attachments, parse `message.raw` with a MIME parser such as `postal-mime`, which the docs use. Then the handler decides what happens to the message, using three methods. ## Forwarding `message.forward(rcptTo, headers?)` relays the message to `rcptTo`. That address must be a **verified destination address** of the account, the same list routing rules use. Points to know: - it returns a promise of an `EmailSendResult` holding a `messageId`, so `await` it; - you may call it **several times**, which is how one address reaches several inboxes; - the optional `Headers` may add only headers whose names start with `X-`, and other headers are removed, so `forward()` cannot rewrite `Subject` or `To`; - forwarded mail is ARC-sealed and its envelope sender is rewritten (SRS), so SPF still passes at the destination; - incoming mail must pass SPF or DKIM; mail that fails both is rejected, and the changelog tells Worker authors to handle a `forward()` that fails for this reason. ## Rejecting `message.setReject(reason)` is synchronous and returns nothing. Email Routing refuses the message with a **permanent SMTP error** that carries your reason back to the server that delivered it. That server then tells its own user that the message bounced. It is different from the two quieter outcomes: - the **Drop** action, set on a routing rule, discards matching mail before any Worker runs; - a handler that returns without forwarding or replying delivers the message to no inbox, and only `setReject()` is documented to send the sender a rejection. Use `setReject()` when the sender should know, for example *No such mailbox* or *Invoices are accepted from registered vendors only*. ## Replying `message.reply()` sends a message straight back on the same SMTP session, threaded with the original. The documented form takes an `EmailMessage`, imported from `cloudflare:email` and constructed as `new EmailMessage(from, to, rawMime)`. The raw MIME string can be written by hand or built with `mimetext`, which needs the `nodejs_compat` flag. The runtime's type definitions also accept a plain builder object with `from`, `subject` and `text` or `html`, and then set the threading headers automatically. `reply()` **throws** unless all of these hold: 1. the incoming email has a valid **DMARC** result; 2. it is the **only reply** in this `email()` event; 3. the reply's recipient is the **original sender**; 4. the reply's sender domain is the **domain that received** the email; 5. the incoming `References` header has **100 entries or fewer**, which stops reply loops. These rules date from March 2025, when Cloudflare relaxed its earlier reply restrictions so that Email Workers could keep a threaded conversation going. Set `In-Reply-To` (and ideally `References`) to the original `Message-ID` so the reply threads. Wrap `reply()` in `try`/`catch` when the sender might be an automated system, because a failed reply should not stop the forward. ## Limits that shape the handler - Messages above **25 MiB** are rejected before the Worker runs, so `rawSize` never exceeds it. - The handler counts against normal **Workers CPU and memory limits**. On the Workers Free plan, a heavy parse can fail with `EXCEEDED_CPU`. - Each routing rule invokes one Worker, but the Worker may branch on `message.to`, which is how one Email Worker serves `support@` and `sales@` together. - If the handler throws before its `forward()` call, the message reaches no inbox. Catch errors and fall back to `forward()` to an admin inbox or `setReject()`, as the docs' error-handling example does. ## Common mistakes - Forwarding to an address that was never verified. - Expecting `forward()` headers to rewrite the subject line. - Replying to a team inbox instead of the sender, or replying twice. - Treating `setReject()` as a silent drop.

  • How does message.setReject() differ from the Drop routing action?
    `setReject(reason)` runs inside the Worker and makes Email Routing answer the sending server with a permanent SMTP error carrying the reason, so the sender learns the message bounced. **Drop** is a routing rule action: matching mail is discarded before any Worker runs, and nobody is told.
  • Why might message.reply() throw on a message that message.forward() handled fine?
    `reply()` has its own rules. The incoming mail needs a valid DMARC result, the reply must go to the original sender, its sender domain must be the receiving domain, only one reply is allowed per event, and the `References` header must have 100 entries or fewer. `forward()` mainly needs a verified destination and authenticated incoming mail.
  • What can the Headers argument of message.forward() change?
    It can only add headers whose names start with `X-`, such as `X-Routed-By`. Any other header in that object is removed, so the subject, recipients and sender of the forwarded message stay as they arrived.

  • message.setReject() silently discards the message, just like the Drop action.
  • message.forward() can send to any address, verified or not.
  • Headers passed to message.forward() can rewrite the Subject or To line.
  • message.reply() can be addressed to anyone, such as the team's shared inbox.
  • An Email Worker can send several replies to one incoming message in one event.

Assumes Email Service as of 2026-10-10; the reply rules (valid DMARC, one reply per event, at most 100 References entries) date from 2025-03-12, when threaded replies from Email Workers were allowed.