cloudflare-email-routing
Complete guide for Cloudflare Email Routing covering both Email Workers (receiving emails) and Send Email bindings (sending emails from Workers). Use when: setting up email routing, creating email workers, processing incoming emails, sending emails from Workers, implementing email allowlists/blocklists, forwarding emails with custom logic, replying to emails automatically, parsing email content, configuring MX records for email, troubleshooting email delivery issues, or encountering email worker errors. Prevents 8 documented issues: "Email Trigger not available" errors, destination address verification bugs, Gmail rate limiting, SPF permerror issues, worker call failures, test event loading issues, activity log discrepancies, and limited debugging on free plans. Keywords: Cloudflare Email Routing, Email Workers, send email, receive email, email forwarding, email allowlist, email blocklist, postal-mime, mimetext, cloudflare:email, EmailMessage, ForwardableEmailMessage, EmailEvent, MX records, SPF, DKIM, email worker binding, send_email binding, wrangler email, email handler, email routing worker, "Email Trigger not available", "failed to call worker", email delivery failed, email not forwarding, destination address not verified
What this skill does
# Cloudflare Email Routing **Status**: Production Ready ✅ **Last Updated**: 2025-10-23 **Latest Versions**: [email protected], [email protected] --- ## What is Cloudflare Email Routing? Cloudflare Email Routing provides two complementary capabilities: 1. **Email Workers** - Receive and process incoming emails with custom logic (allowlists, blocklists, forwarding, parsing, replying) 2. **Send Email** - Send emails from Workers to verified destination addresses (notifications, alerts, confirmations) Both capabilities are **free** and work together to enable complete email functionality in Cloudflare Workers. --- ## Quick Start (10 Minutes) ### Part 1: Enable Email Routing (Dashboard) **Prerequisites**: Domain must be on Cloudflare DNS 1. Log in to Cloudflare Dashboard → select your domain 2. Go to **Email** > **Email Routing** 3. Select **Enable Email Routing** → **Add records and enable** - This automatically adds MX records, SPF, and DKIM to your DNS 4. Create a destination address: - **Custom address**: `[email protected]` - **Destination**: Your personal email (e.g., `[email protected]`) - **Verify** the destination address via email 5. ✅ Basic email forwarding is now active **What you just did**: Configured DNS and basic forwarding. Now let's add Workers for custom logic. --- ### Part 2: Receiving Emails with Email Workers #### 1. Install Dependencies ```bash npm install [email protected] [email protected] ``` **Why these packages:** - `postal-mime` - Parse incoming email messages (headers, body, attachments) - `mimetext` - Create email messages for sending/replying #### 2. Create Email Worker Create `src/email.ts`: ```typescript import { EmailMessage } from 'cloudflare:email'; import PostalMime from 'postal-mime'; export default { async email(message, env, ctx) { // Parse the incoming message const parser = new PostalMime.default(); const email = await parser.parse(await new Response(message.raw).arrayBuffer()); console.log('From:', message.from); console.log('To:', message.to); console.log('Subject:', email.subject); // Forward to verified destination await message.forward('[email protected]'); }, }; ``` #### 3. Configure Wrangler Update `wrangler.jsonc`: ```jsonc { "name": "email-worker", "main": "src/email.ts", "compatibility_date": "2025-10-11" } ``` #### 4. Deploy and Bind ```bash npx wrangler deploy # In Cloudflare Dashboard: # Email > Email Routing > Email Workers # Select your worker → Create route → Enter address (e.g., [email protected]) ``` **What you just did**: Created a Worker that logs and forwards emails. --- ### Part 3: Sending Emails from Workers #### 1. Configure Send Email Binding Update `wrangler.jsonc`: ```jsonc { "name": "my-worker", "main": "src/index.ts", "compatibility_date": "2025-10-11", "send_email": [ { "name": "EMAIL", "destination_address": "[email protected]" } ] } ``` **CRITICAL**: `destination_address` must be: - A domain where you have Email Routing enabled - A verified destination address in Email Routing settings #### 2. Send Email from Worker ```typescript import { EmailMessage } from 'cloudflare:email'; import { createMimeMessage } from 'mimetext'; export default { async fetch(request, env, ctx) { // Create email message const msg = createMimeMessage(); msg.setSender({ name: 'My App', addr: '[email protected]' }); msg.setRecipient('[email protected]'); msg.setSubject('Welcome to My App'); msg.addMessage({ contentType: 'text/plain', data: 'Thank you for signing up!', }); // Send via binding const message = new EmailMessage( '[email protected]', '[email protected]', msg.asRaw() ); await env.EMAIL.send(message); return new Response('Email sent!'); }, }; ``` #### 3. Deploy ```bash npx wrangler deploy ``` **What you just did**: Configured your Worker to send emails to verified addresses. --- ## Email Workers: Complete Guide ### Runtime API #### EmailEvent Handler ```typescript export default { async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) { // Process email here }, }; ``` **Parameters:** - `message` - ForwardableEmailMessage object - `env` - Environment bindings (KV, D1, secrets, etc.) - `ctx` - Execution context (waitUntil for async operations) #### ForwardableEmailMessage Properties ```typescript interface ForwardableEmailMessage { readonly from: string; // Sender email readonly to: string; // Recipient email readonly headers: Headers; // Email headers readonly raw: ReadableStream; // Raw email message readonly rawSize: number; // Size in bytes // Methods setReject(reason: string): void; forward(rcptTo: string, headers?: Headers): Promise<void>; reply(message: EmailMessage): Promise<void>; } ``` --- ## Common Patterns ### Pattern 1: Allowlist Only accept emails from approved senders: ```typescript export default { async email(message, env, ctx) { const allowList = [ '[email protected]', '[email protected]', '[email protected]', ]; if (!allowList.includes(message.from)) { message.setReject('Address not on allowlist'); return; } await message.forward('[email protected]'); }, }; ``` **When to use**: Contact forms, private email addresses, team inboxes --- ### Pattern 2: Blocklist Reject emails from specific senders or domains: ```typescript export default { async email(message, env, ctx) { const blockList = [ '[email protected]', '@suspicious-domain.com', // Block entire domain ]; const isBlocked = blockList.some(pattern => message.from.includes(pattern) ); if (isBlocked) { message.setReject('Sender blocked'); return; } await message.forward('[email protected]'); }, }; ``` **When to use**: Spam filtering, blocking harassers, domain-level blocks --- ### Pattern 3: Parse and Store Extract email content and store in D1 or KV: ```typescript import PostalMime from 'postal-mime'; export default { async email(message, env, ctx) { // Parse email const parser = new PostalMime.default(); const rawEmail = new Response(message.raw); const email = await parser.parse(await rawEmail.arrayBuffer()); // Store in D1 await env.DB.prepare( 'INSERT INTO emails (from_addr, subject, text, received_at) VALUES (?, ?, ?, ?)' ).bind( message.from, email.subject, email.text, new Date().toISOString() ).run(); // Forward to inbox await message.forward('[email protected]'); }, }; ``` **When to use**: Email archiving, ticket systems, support inboxes, audit logs --- ### Pattern 4: Auto-Reply Send automatic replies with custom logic: ```typescript import PostalMime from 'postal-mime'; import { createMimeMessage } from 'mimetext'; import { EmailMessage } from 'cloudflare:email'; export default { async email(message, env, ctx) { // Parse incoming email const parser = new PostalMime.default(); const email = await parser.parse(await new Response(message.raw).arrayBuffer()); // Create reply const msg = createMimeMessage(); msg.setSender({ name: 'Support Team', addr: '[email protected]' }); msg.setRecipient(message.from); msg.setHeader('In-Reply-To', message.headers.get('Message-ID')); msg.setSubject(`Re: ${email.subject}`); msg.addMessage({ contentType: 'text/plain', data: `Thank you for your message about "${email.subject}". We'll respond within 24 hours.`, }); // Send reply const replyMessage = new EmailMessage( '[email protected]', message.from, msg.asRaw() ); await message.reply(replyMessage); // Also forward to team inbox await message.forward('[email protected]'); }, };
Related in Cloud & DevOps
appbuilder-action-scaffolder
IncludedCreate, implement, deploy, and debug Adobe Runtime actions with consistent layout, validation, and error handling. Use this skill whenever the user needs to add actions to an App Builder project, understand action structure (params, response format, web/raw actions), configure actions in the manifest, use App Builder SDKs (State, Files, Events, database), deploy and invoke actions via CLI, debug action issues, or implement patterns such as webhook receivers, custom event providers, journaling consumers, large payload redirects, action sequence pipelines, and Asset Compute workers. Also trigger when users mention serverless functions in Adobe context, action logging, IMS authentication for actions, or cron-style scheduled actions.
orchestrating-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. Use this skill when the user needs a multi-step Data Cloud pipeline, cross-phase troubleshooting, or data space and data kit management. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase sf data360 workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching phase-specific skill), the task is STDM/session tracing/parquet telemetry (use observing-agentforce), standard CRM SOQL (use querying-soql), or Apex implementation (use generating-apex).
github-project-automation
IncludedAutomate GitHub repository setup with CI/CD workflows, issue templates, Dependabot, and CodeQL security scanning. Includes 12 production-tested workflows and prevents 18 errors: YAML syntax, action pinning, and configuration. Use when: setting up GitHub Actions CI/CD, creating issue/PR templates, enabling Dependabot or CodeQL scanning, deploying to Cloudflare Workers, implementing matrix testing, or troubleshooting YAML indentation, action version pinning, secrets syntax, runner versions, or CodeQL configuration. Keywords: github actions, github workflow, ci/cd, issue templates, pull request templates, dependabot, codeql, security scanning, yaml syntax, github automation, repository setup, workflow templates, github actions matrix, secrets management, branch protection, codeowners, github projects, continuous integration, continuous deployment, workflow syntax error, action version pinning, runner version, github context, yaml indentation error
sf-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase `sf data360` workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching sf-datacloud-* skill), the task is STDM/session tracing/parquet telemetry (use sf-ai-agentforce-observability), standard CRM SOQL (use sf-soql), or Apex implementation (use sf-apex).
fabric-cli
IncludedUse this skill for Fabric.so CLI workflows with the `fabric` terminal command: diagnose/install/login, search or browse a Fabric library, save notes/links/files, create folders, ask the Fabric AI assistant, manage tasks/workspaces, generate shell completion, check subscription usage, produce JSON output, and use Fabric as persistent agent memory. Do not use for Microsoft Fabric/Azure/Power BI `fab`, Daniel Miessler's Fabric framework, Python Fabric SSH, Fabric.js, or textile/fashion fabric.
lark
IncludedLark/Feishu CLI skills: lark-cli operations for docs, markdown, sheets, base, calendar, im, mail, task, okr, drive, wiki, slides, whiteboard, apps, approval, attendance, contact, vc, minutes, event. Use when the user needs to operate Lark/Feishu resources via lark-cli, send messages, manage documents, spreadsheets, calendars, tasks, OKRs, deploy web pages, or any Feishu/Lark workspace operations.