Cloudflare Email Routing logo

Cloudflare Email Routing

Community
secondsky
cloudflare-email-routing

Cloudflare Email Routing for receiving/sending emails via Workers. Use for email workers, forwarding, allowlists, or encountering Email Trigger errors, worker call failures, SPF issues.

Overview

Publishersecondsky
Repositoryclaude-skills
Skill namecloudflare-email-routing
Stars
219
Forks
31
Bundled files
11
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 11 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by secondsky on GitHub. Read the source before you install it.

Installation

Install the Cloudflare Email Routing AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/secondsky/claude-skills.git /tmp/claude-skills
mkdir -p .claude/skills
cp -r /tmp/claude-skills/plugins/cloudflare-email-routing/skills/cloudflare-email-routing .claude/skills/cloudflare-email-routing
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Cloudflare Email Routing in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Cloudflare Email Routing on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Cloudflare Email Routing is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Cloudflare Email Routing

Status: Production Ready ✅ | Last Verified: 2025-11-18


What Is Email Routing?

Two capabilities:

  1. Email Workers - Receive and process incoming emails (allowlists, forwarding, parsing)
  2. Send Email - Send emails from Workers to verified addresses

Both free and work together for complete email functionality.


Quick Start (10 Minutes)

Part 1: Enable Email Routing

Dashboard setup:

  1. Dashboard → Domain → EmailEmail Routing
  2. Enable Email RoutingAdd records and enable
  3. Create destination address:
    • Custom: hello@yourdomain.com
    • Destination: Your email
    • Verify via email
  4. ✅ Basic forwarding active

Part 2: Receiving Emails (Email Workers)

Install dependencies:

bash
bun add postal-mime@2.5.0 mimetext@3.0.27

Create email worker:

typescript
// src/email.ts
import { EmailMessage } from 'cloudflare:email';
import PostalMime from 'postal-mime';

export default {
  async email(message, env, ctx) {
    const parser = new PostalMime.default();
    const email = await parser.parse(await new Response(message.raw).arrayBuffer());

    console.log('From:', message.from);
    console.log('Subject:', email.subject);

    // Forward to destination
    await message.forward('you@gmail.com');
  }
};

Configure wrangler.jsonc:

jsonc
{
  "name": "email-worker",
  "main": "src/email.ts",
  "compatibility_date": "2025-10-11",  // must be >= 2024-09-23 for nodejs_compat
  "compatibility_flags": ["nodejs_compat"]  // Required! postal-mime needs Node.js compat
}

Deploy and connect:

bash
bunx wrangler deploy

Dashboard → Email Workers → Create address → Select worker

Part 3: Sending Emails

Add send email binding:

jsonc
{
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2025-10-11",
  "send_email": [
    {
      "name": "SES",
      "destination_address": "user@example.com"
    }
  ]
}

Send from worker:

typescript
import { EmailMessage } from 'cloudflare:email';
import { createMimeMessage } from 'mimetext';

const msg = createMimeMessage();
msg.setSender({ name: 'App', addr: 'noreply@yourdomain.com' });
msg.setRecipient('user@example.com');
msg.setSubject('Hello!');
msg.addMessage({
  contentType: 'text/plain',
  data: 'Email body here'
});

const message = new EmailMessage(
  'noreply@yourdomain.com',
  'user@example.com',
  msg.asRaw()
);

await env.SES.send(message);

Load references/setup-guide.md for complete walkthrough.


Critical Rules

Always Do ✅

  1. Enable compatibility_flags: ["nodejs_compat"] for postal-mime (requires compatibility_date >= 2024-09-23)
  2. Verify destination addresses before sending
  3. Parse with postal-mime for email content
  4. Use mimetext for creating emails
  5. Check message.from for allowlists
  6. Forward with message.forward() (not manual)
  7. Handle errors (email delivery can fail)
  8. Test with real emails (not just dashboard)
  9. Add MX records (automatic via dashboard)
  10. Log email activity for debugging

Never Do ❌

  1. Never skip nodejs_compat (postal-mime requires the Node.js compat flag)
  2. Never send without verification (delivery fails)
  3. Never hardcode email addresses in public code
  4. Never skip parsing (raw email is hard to work with)
  5. Never ignore spam (implement allowlists/blocklists)
  6. Never exceed Gmail limits (500 emails/day to Gmail)
  7. Never skip error handling (emails can fail)
  8. Never modify DNS manually (use dashboard)
  9. Never expose email content in logs (PII)
  10. Never assume instant delivery (email is async)

Common Patterns

Allowlist

typescript
const allowlist = ['approved@domain.com'];

if (!allowlist.includes(message.from)) {
  message.setReject('Not on allowlist');
  return;
}

await message.forward('you@gmail.com');

Blocklist

typescript
const blocklist = ['spam@bad.com'];

if (blocklist.includes(message.from)) {
  message.setReject('Blocked');
  return;
}

await message.forward('you@gmail.com');

Reply to Email

typescript
const msg = createMimeMessage();
msg.setSender({ addr: 'noreply@yourdomain.com' });
msg.setRecipient(message.from);
msg.setSubject(`Re: ${email.subject}`);
msg.addMessage({
  contentType: 'text/plain',
  data: 'Thanks for your email!'
});

const reply = new EmailMessage(
  'noreply@yourdomain.com',
  message.from,
  msg.asRaw()
);

await env.SES.send(reply);

Parse Attachments

typescript
const parser = new PostalMime.default();
const email = await parser.parse(await new Response(message.raw).arrayBuffer());

for (const attachment of email.attachments) {
  console.log('Filename:', attachment.filename);
  console.log('Type:', attachment.mimeType);
  console.log('Size:', attachment.content.byteLength);
}

Custom Routing Logic

typescript
async email(message, env, ctx) {
  const parser = new PostalMime.default();
  const email = await parser.parse(await new Response(message.raw).arrayBuffer());

  // Route based on subject
  if (email.subject.includes('[Support]')) {
    await message.forward('support@yourdomain.com');
  } else if (email.subject.includes('[Sales]')) {
    await message.forward('sales@yourdomain.com');
  } else {
    await message.forward('general@yourdomain.com');
  }
}

Email Message Properties

Incoming Messages (ForwardableEmailMessage)

typescript
message.from        // Sender email
message.to          // Recipient email
message.headers     // Email headers
message.raw         // Raw email stream
message.rawSize     // Size in bytes

// Methods
message.forward(address)        // Forward to address
message.setReject(reason)       // Reject email

Parsed Email (PostalMime)

typescript
email.from          // { name, address }
email.to            // [{ name, address }]
email.subject       // Subject line
email.text          // Plain text body
email.html          // HTML body
email.attachments   // Array of attachments
email.headers       // All headers

Top 5 Errors Prevented

  1. "Email Trigger not available": Enable compatibility_flags: ["nodejs_compat"] (with compatibility_date >= 2024-09-23)
  2. Destination not verified: Verify all send destinations
  3. Gmail rate limit: Max 500 emails/day to Gmail
  4. SPF permerror: Use dashboard to configure DNS
  5. Worker call failed: Check logs for parsing errors

Use Cases

Use Case 1: Support Ticket System

typescript
async email(message, env, ctx) {
  const parser = new PostalMime.default();
  const email = await parser.parse(await new Response(message.raw).arrayBuffer());

  // Create ticket in database
  await env.DB.prepare(
    'INSERT INTO tickets (email, subject, body, created_at) VALUES (?, ?, ?, ?)'
  ).bind(message.from, email.subject, email.text, Date.now()).run();

  // Send confirmation
  const msg = createMimeMessage();
  msg.setSender({ addr: 'support@yourdomain.com' });
  msg.setRecipient(message.from);
  msg.setSubject('Ticket Created');
  msg.addMessage({
    contentType: 'text/plain',
    data: 'Your support ticket has been created.'
  });

  const confirmation = new EmailMessage(
    'support@yourdomain.com',
    message.from,
    msg.asRaw()
  );

  await env.SES.send(confirmation);
}

Use Case 2: Email Notifications

typescript
export default {
  async fetch(request, env, ctx) {
    // User signup
    const { email, name } = await request.json();

    const msg = createMimeMessage();
    msg.setSender({ name: 'App', addr: 'noreply@yourdomain.com' });
    msg.setRecipient(email);
    msg.setSubject('Welcome!');
    msg.addMessage({
      contentType: 'text/html',
      data: `<h1>Welcome, ${name}!</h1>`
    });

    const message = new EmailMessage(
      'noreply@yourdomain.com',
      email,
      msg.asRaw()
    );

    await env.SES.send(message);

    return new Response('Welcome email sent!');
  }
};

Use Case 3: Email Forwarding with Filtering

typescript
async email(message, env, ctx) {
  const parser = new PostalMime.default();
  const email = await parser.parse(await new Response(message.raw).arrayBuffer());

  // Filter spam keywords
  const spamKeywords = ['viagra', 'lottery', 'prince'];
  const isSpam = spamKeywords.some(keyword =>
    email.subject.toLowerCase().includes(keyword) ||
    email.text.toLowerCase().includes(keyword)
  );

  if (isSpam) {
    message.setReject('Spam detected');
    return;
  }

  await message.forward('you@gmail.com');
}

When to Load References

Load references/setup-guide.md when:

  • First-time Email Routing setup
  • Configuring MX records
  • Setting up email workers
  • Configuring send email binding
  • Complete walkthrough needed

Using Bundled Resources

References (references/):

  • setup-guide.md - Complete setup walkthrough (enabling routing, email workers, send email)
  • common-errors.md - All 8 documented errors with solutions and prevention
  • dns-setup.md - MX records, SPF, DKIM configuration guide
  • local-development.md - Local testing and development patterns

Templates (templates/):

  • receive-basic.ts - Basic email receiving worker
  • receive-allowlist.ts - Email allowlist implementation
  • receive-blocklist.ts - Email blocklist implementation
  • receive-reply.ts - Auto-reply email worker
  • send-basic.ts - Basic send email example
  • send-notification.ts - Notification email pattern
  • wrangler-email.jsonc - Wrangler configuration for email routing

Official Documentation


Questions? Issues?

  1. Check references/setup-guide.md for complete setup
  2. Verify compatibility_flags: ["nodejs_compat"] in wrangler.jsonc
  3. Confirm destination addresses verified
  4. Check logs for errors

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Cloudflare Email Routing AI skill do?

Cloudflare Email Routing for receiving/sending emails via Workers. Use for email workers, forwarding, allowlists, or encountering Email Trigger errors, worker call failures, SPF issues.

Why use Cloudflare Email Routing on TypingMind?

Because you install it once and use it with any model. Cloudflare Email Routing is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Cloudflare Email Routing in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/secondsky/claude-skills/tree/main/plugins/cloudflare-email-routing/skills/cloudflare-email-routing. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Cloudflare Email Routing?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Cloudflare Email Routing?

As many as you like. As long as a model supports skills, you can use Cloudflare Email Routing with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Cloudflare Email Routing AI skill free?

Yes. It is published on GitHub by secondsky under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇