Skip to content

Workers API

Process incoming emails with the email() handler in Cloudflare Workers. Forward, reply, reject, or process emails programmatically.

Process incoming emails using the email() handler in your Cloudflare Workers. This allows you to programmatically handle email routing with custom logic.

Email handler syntax

Add the email handler function to your Worker's exported handlers:

export default {
	async email(message, env, ctx): Promise<void> {
		// Process incoming email
		await message.forward("destination@example.com");
	},
} satisfies ExportedHandler<Env>;
from workers import WorkerEntrypoint

class Default(WorkerEntrypoint):
    async def email(self, message, env, ctx):
        await message.forward("destination@example.com")

Parameters

Parameter Type Description
message ForwardableEmailMessage The incoming email message
env object Worker environment bindings (KV, EMAIL, etc.)
ctx object Execution context with waitUntil function

ForwardableEmailMessage interface

The message parameter provides access to the incoming email:

interface ForwardableEmailMessage {
	readonly from: string; // Sender email address (envelope MAIL FROM)
	readonly to: string; // Recipient email address (envelope RCPT TO)
	readonly headers: Headers; // Email headers (Subject, Message-ID, etc.)
	readonly raw: ReadableStream; // Raw MIME email content stream
	readonly rawSize: number; // Size of raw email in bytes
	readonly canBeForwarded: boolean; // Whether the message can be forwarded

	// Actions
	setReject(reason: string): void;
	forward(rcptTo: string, headers?: Headers): Promise<EmailSendResult>;
	reply(
		message: EmailReplyMessageBuilder | EmailMessage,
	): Promise<EmailSendResult>;
}

// Structured reply builder (recommended)
interface EmailReplyMessageBuilder {
	from: string | EmailAddress;
	subject: string;
	text?: string;
	html?: string;
	replyTo?: string | EmailAddress;
	attachments?: Attachment[];
	// Custom headers. See /email-service/reference/headers/
	headers?: { [key: string]: string };
}

EmailAddress and Attachment are the same types that the Email Sending Workers API uses.

Properties

export default {
	async email(message, env, ctx): Promise<void> {
		// Access email metadata
		console.log(`From: ${message.from}`);
		console.log(`To: ${message.to}`);
		console.log(`Size: ${message.rawSize} bytes`);

		// Access headers
		const subject = message.headers.get("subject");
		const date = message.headers.get("date");
		const messageId = message.headers.get("message-id");

		console.log(`Subject: ${subject}`);
		console.log(`Date: ${date}`);
		console.log(`Message-ID: ${messageId}`);
	},
};

Use postal-mime ↗︎ to parse the MIME structure of an incoming email. The parser handles multipart boundaries, transfer encodings, and character sets correctly.

message.raw is a single-use ReadableStream. Parse it once and reuse the parsed result.

import PostalMime from "postal-mime";

export default {
	async email(message, env, ctx): Promise<void> {
		const email = await PostalMime.parse(message.raw);

		console.log(`Subject: ${email.subject}`);
		console.log(`Text: ${email.text}`);
		console.log(`HTML: ${email.html}`);
	},
};

Authentication results

When Cloudflare is the receiving mail exchanger (MX) for your domain, Email Routing checks Sender Policy Framework (SPF), DomainKeys Identified Mail (DKIM), and Domain-based Message Authentication, Reporting & Conformance (DMARC) before it invokes your Worker. It prepends an Authentication-Results ↗︎ header with its results.

A simplified header with passing results looks like this:

Authentication-Results: mx.cloudflare.net; spf=pass; dkim=pass; dmarc=pass

Verify Authentication-Results headers

Do not use message.headers.get("authentication-results") to make authentication decisions. Headers joins repeated fields into one string, so you cannot reliably tell where Cloudflare's field ends. The authentication service identifier (authserv-id) does not establish who added a field.

If your Worker receives mail through Cloudflare as the receiving MX, read the individual header fields from message.raw with a MIME parser that preserves their order. Use an RFC 8601 parser to read only the first Authentication-Results field and verify that its authserv-id is mx.cloudflare.net. If that field is missing, does not parse, or has a different identifier, treat Cloudflare's results as unavailable. Do not search later fields for a match.

SPF can report separate results for HELO and MAIL FROM, and DKIM can report one result per signature. An SPF or DKIM pass alone does not show that the authenticated domain aligns with the domain in the message's From header. Use the DMARC result if your policy requires that alignment.

Your Worker does not need to verify Authenticated Received Chain (ARC) to read the results Cloudflare adds on this receiving path. ARC helps downstream mail servers evaluate authentication after forwarding.

Email actions

Forward emails

Forward incoming emails to verified destination addresses:

export default {
	async email(message, env, ctx): Promise<void> {
		// Forward to a single address
		await message.forward("team@example.com");
	},
};
export default {
	async email(message, env, ctx): Promise<void> {
		const recipient = message.to;
		const subject = message.headers.get("subject") || "";

		// Route based on recipient
		if (recipient.includes("support@")) {
			await message.forward("support-team@example.com");
		} else if (recipient.includes("sales@")) {
			await message.forward("sales-team@example.com");
		} else if (subject.toLowerCase().includes("urgent")) {
			await message.forward("urgent@example.com");
		} else {
			// Default routing
			await message.forward("general@example.com");
		}
	},
};
export default {
	async email(message, env, ctx): Promise<void> {
		const subject = message.headers.get("subject") || "";

		if (subject.toLowerCase().includes("security")) {
			// Forward to multiple addresses for security issues
			await Promise.all([
				message.forward("security@example.com"),
				message.forward("admin@example.com"),
				message.forward("ciso@example.com"),
			]);
		} else {
			await message.forward("general@example.com");
		}
	},
};

Forward with custom headers

Add custom headers when forwarding. Only headers with an X- prefix can be added through forward(). Other headers are removed.

export default {
	async email(message, env, ctx): Promise<void> {
		// Create custom headers
		const customHeaders = new Headers();
		customHeaders.set("X-Processed-By", "Email-Worker");
		customHeaders.set("X-Processing-Time", new Date().toISOString());
		customHeaders.set("X-Original-Recipient", message.to);
		customHeaders.set("X-Spam-Score", "0.1"); // Example spam score

		// Forward with custom headers
		await message.forward("processed@example.com", customHeaders);
	},
};

Reply to emails

Send automatic replies with message.reply(). Replies are threaded with the original message and pass through the same SMTP session, so they preserve the original Message-ID chain.

reply() accepts two payload forms:

  • Message builder (recommended): An EmailReplyMessageBuilder object with from, subject, and the message body. The reply goes to the sender of the incoming email, so the builder has no to, cc, or bcc fields.
  • Raw MIME message: An EmailMessage built from a raw MIME string. Use this form when you already build MIME messages. Refer to Reply with a raw MIME message.

In both forms, Email Service sets the In-Reply-To and References headers from the incoming email. If you set either header yourself, its value must match the value Email Service computes.

Replies through the Workers API must satisfy the following requirements, otherwise reply() throws an exception:

  • The incoming email must have a valid DMARC result.
  • An email can only be replied to once per EmailMessage event. A failed reply() call also counts as the one reply.
  • With a raw EmailMessage, the recipient in the reply must match the sender of the incoming email.
  • The outgoing sender domain must match the domain that received the email.
  • The reply is rejected if the incoming email has more than 100 entries in its References header, to prevent reply loops and abuse.
export default {
	async email(message, env, ctx): Promise<void> {
		const subject = message.headers.get("subject") || "";

		await message.reply({
			from: message.to,
			subject: `Re: ${subject}`,
			text: "Thank you for your message. We have received your email and will respond shortly.",
			html: "<h1>Thank you for your message</h1><p>We have received your email and will respond shortly.</p>",
		});

		// Also forward to human team
		await message.forward("team@example.com");
	},
};
export default {
	async email(message, env, ctx): Promise<void> {
		const sender = message.from;
		const recipient = message.to;
		const subject = message.headers.get("subject") || "";

		// Do not reply to automated emails
		if (
			sender.includes("noreply") ||
			sender.includes("no-reply") ||
			subject.toLowerCase().includes("automated")
		) {
			await message.forward("team@example.com");
			return;
		}

		// Customized auto-reply based on recipient
		let html = "";

		if (recipient.includes("support@")) {
			html = `
                <h1>Support Request Received</h1>
                <p>Thank you for contacting support. Your request has been assigned ticket #${Date.now()}.</p>
                <p>Expected response time: 2-4 hours during business hours.</p>
            `;
		} else if (recipient.includes("sales@")) {
			html = `
                <h1>Sales Inquiry Received</h1>
                <p>Thank you for your interest in our products.</p>
                <p>A sales representative will contact you within 24 hours.</p>
            `;
		} else {
			html = `
                <h1>Message Received</h1>
                <p>Thank you for your message. We will respond within 2 business days.</p>
            `;
		}

		await message.reply({
			from: recipient,
			subject: `Re: ${subject}`,
			text: html.replace(/<[^>]*>/g, ""),
			html,
		});

		// Forward to appropriate team
		await message.forward("team@example.com");
	},
};

Reply with a raw MIME message

Pass an EmailMessage to reply() to send a MIME message that you build yourself. The following example uses mimetext ↗︎ to build the MIME body. The mimetext package requires the nodejs_compat compatibility flag.

import { EmailMessage } from "cloudflare:email";
import { createMimeMessage } from "mimetext";

export default {
	async email(message, env, ctx): Promise<void> {
		const subject = message.headers.get("subject") || "";
		const messageId = message.headers.get("Message-ID");

		const reply = createMimeMessage();
		if (messageId) {
			reply.setHeader("In-Reply-To", messageId);
			reply.setHeader("References", messageId);
		}
		reply.setSender(message.to);
		reply.setRecipient(message.from);
		reply.setSubject(`Re: ${subject}`);
		reply.addMessage({
			contentType: "text/plain",
			data: "Thank you for your message. We have received your email and will respond shortly.",
		});

		await message.reply(
			new EmailMessage(message.to, message.from, reply.asRaw()),
		);
	},
};

Reply errors

reply() throws errors with the same code property as send(). The following codes are specific to replies:

Error code Common causes
E_TEMPORARY_AUTHENTICATION_ERROR Authentication of the incoming email failed temporarily.
E_FIELD_MISSING The incoming email has no Message-ID header, so the reply cannot be threaded.

Reject emails

Call message.setReject(reason) to reject an email with a permanent 5xx SMTP error. The sending mail server should not retry the same delivery.

Use setReject() only for intentional permanent rejections, such as unauthorized senders, invalid recipients, failed authentication checks, or policy violations. For transient errors that the sending mail server should retry, let an exception propagate instead of calling setReject(). Refer to Error handling.

export default {
	async email(message, env, ctx): Promise<void> {
		const sender = message.from;

		// Block specific senders
		const blockedDomains = ["spam.com", "unwanted.net"];
		const senderDomain = sender.split("@")[1];

		if (blockedDomains.includes(senderDomain)) {
			message.setReject("Sender domain not allowed");
			return;
		}

		// Continue processing
		await message.forward("inbox@example.com");
	},
};
export default {
	async email(message, env, ctx): Promise<void> {
		const subject = message.headers.get("subject") || "";

		// Reject based on subject content
		const spamKeywords = ["buy now", "limited time", "act fast", "urgent"];
		const containsSpam = spamKeywords.some((keyword) =>
			subject.toLowerCase().includes(keyword),
		);

		if (containsSpam) {
			message.setReject("Message appears to be spam");
			return;
		}

		// Check message size
		if (message.rawSize > 25 * 1024 * 1024) {
			// 25 MiB limit (inbound message size)
			message.setReject("Message too large");
			return;
		}

		// Continue processing
		await message.forward("inbox@example.com");
	},
};

Error handling

Use message.setReject() for an intentional, permanent rejection. For a transient failure, such as a database outage or a forwarding timeout, let the error propagate. Cloudflare returns a temporary 4xx SMTP response, so the sending mail server can retry according to its own retry policy. If you catch the error to log it, rethrow it instead of calling message.setReject().

This example forwards mail for contact@example.com to a verified destination address:

export default {
	async email(message) {
		if (message.to !== "contact@example.com") {
			message.setReject("This route only accepts mail for contact@example.com");
			return;
		}

		try {
			await message.forward("inbox@example.com");
		} catch (error) {
			console.error("Email forwarding failed", error);
			throw error;
		}
	},
};
export default {
	async email(message): Promise<void> {
		if (message.to !== "contact@example.com") {
			message.setReject("This route only accepts mail for contact@example.com");
			return;
		}

		try {
			await message.forward("inbox@example.com");
		} catch (error) {
			console.error("Email forwarding failed", error);
			throw error;
		}
	},
} satisfies ExportedHandler;

SMTP replies and retries

Work you pass to ctx.waitUntil() can delay the final SMTP reply even after your email() function returns. Do not use ctx.waitUntil() to run work after the reply. If the sending server times out while waiting for the reply, it can retry even if your handler already completed its work.

Each invocation handles one envelope recipient (message.to). If one SMTP transaction has multiple recipients, the sending server receives one final reply for the message ↗︎, not one reply per Worker invocation. A later recipient can fail after your handler has already processed an earlier recipient. A retry can invoke your handler for that earlier recipient again.

Handle redelivery

Design your handler so a retry does not repeat work that already succeeded. If a service you call supports idempotency keys, reuse the same key on retries. Do not record work as complete before it succeeds, or a retry can skip unfinished work.

Senders can omit Message-ID or reuse it for different messages. If you use it to detect possible duplicates, scope it to the envelope recipient and do not treat a missing ID as a match. Do not use a hash of message.raw as a fallback: transit headers such as Received can change between attempts.

Next steps

Was this helpful?