Cloudflare Workers allows you to run serverless JavaScript code at the edge. One of its most powerful (yet underutilized) features is Email Routing integration, which lets you handle incoming SMTP mail directly in a serverless function. Here is how to build a custom processing pipeline.
Step 1: Configure Email Routing
In your Cloudflare dashboard, enable Email Routing for your domain. Set up a catch-all route or a specific address and set the action to "Send to Worker." Select your deployed worker from the dropdown list.
Step 2: The Worker Script
Your Cloudflare Worker intercepts the raw email stream. The standard handler function looks like this:
export default {
async email(message, env, ctx) {
const rawEmail = await message.raw;
// Parse the email headers
const sender = message.headers.get("from");
const subject = message.headers.get("subject");
// Send a webhook to your main web server
await fetch("https://api.yourdomain.com/webhook", {
method: "POST",
body: JSON.stringify({ sender, subject, raw: rawEmail }),
headers: { "Content-Type": "application/json" }
});
}
}
Step 3: Edge-side Security
Because the Worker runs at Cloudflare's edge, you can block bad actors, spam networks, or specific domains before they ever touch your main server database, saving you bandwidth, CPU cycles, and keeping your application incredibly secure.