Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/email-workers/README.md
1# Cloudflare Email Workers23Process incoming emails programmatically using Cloudflare Workers runtime.45## Overview67Email Workers enable custom email processing logic at the edge. Build spam filters, auto-responders, ticket systems, notification handlers, and more using the same Workers runtime you use for HTTP requests.89**Key capabilities**:10- Process inbound emails with full message access11- Forward to verified destinations12- Send replies with proper threading13- Parse MIME content and attachments14- Integrate with KV, R2, D1, and external APIs1516## Quick Start1718### Minimal ES Modules Handler1920```typescript21export default {22async email(message, env, ctx) {23// Reject spam24if (message.from.includes('spam.com')) {25message.setReject('Blocked');26return;27}2829// Forward to inbox30await message.forward('[email protected]');31}32};33```3435### Core Operations3637| Operation | Method | Use Case |38|-----------|--------|----------|39| Forward | `message.forward(to, headers?)` | Route to verified destination |40| Reject | `message.setReject(reason)` | Block with SMTP error |41| Reply | `message.reply(emailMessage)` | Auto-respond with threading |42| Parse | postal-mime library | Extract subject, body, attachments |4344## Reading Order4546For comprehensive understanding, read files in this order:47481. **README.md** (this file) - Overview and quick start492. **configuration.md** - Setup, deployment, bindings503. **api.md** - Complete API reference514. **patterns.md** - Real-world implementation examples525. **gotchas.md** - Critical pitfalls and debugging5354## In This Reference5556| File | Description | Key Topics |57|------|-------------|------------|58| [api.md](./api.md) | Complete API reference | ForwardableEmailMessage, SendEmail bindings, reply() method, postal-mime/mimetext APIs |59| [configuration.md](./configuration.md) | Setup and configuration | wrangler.jsonc, bindings, deployment, dependencies |60| [patterns.md](./patterns.md) | Real-world examples | Allowlists from KV, auto-reply with threading, attachment extraction, webhook notifications |61| [gotchas.md](./gotchas.md) | Pitfalls and debugging | Stream consumption, ctx.waitUntil errors, security, limits |6263## Architecture6465```66Incoming Email → Email Routing → Email Worker67↓68Process + Decide69↓70┌───────────────┼───────────────┐71↓ ↓ ↓72Forward Reply Reject73```7475**Event flow**:761. Email arrives at your domain772. Email Routing matches route (e.g., `[email protected]`)783. Bound Email Worker receives `ForwardableEmailMessage`794. Worker processes and takes action (forward/reply/reject)805. Email delivered or rejected based on worker logic8182## Key Concepts8384### Envelope vs Headers8586- **Envelope addresses** (`message.from`, `message.to`): SMTP transport addresses (trusted)87- **Header addresses** (parsed from body): Display addresses (can be spoofed)8889Use envelope addresses for security decisions.9091### Single-Use Streams9293`message.raw` is a ReadableStream that can only be read once. Buffer to ArrayBuffer for multiple uses.9495```typescript96// Buffer first97const buffer = await new Response(message.raw).arrayBuffer();98const email = await PostalMime.parse(buffer);99```100101See [gotchas.md](./gotchas.md#readablestream-can-only-be-consumed-once) for details.102103### Verified Destinations104105`forward()` only works with addresses verified in the Cloudflare Email Routing dashboard. Add destinations before deployment.106107## Use Cases108109- **Spam filtering**: Block based on sender, content, or reputation110- **Auto-responders**: Send acknowledgment replies with threading111- **Ticket creation**: Parse emails and create support tickets112- **Email archival**: Store in KV, R2, or D1113- **Notification routing**: Forward to Slack, Discord, or webhooks114- **Attachment processing**: Extract files to R2 storage115- **Multi-tenant routing**: Route based on recipient subdomain116- **Size filtering**: Reject oversized attachments117118## Limits119120| Limit | Value |121|-------|-------|122| Max message size | 25 MiB |123| Max routing rules | 200 |124| Max destinations | 200 |125| CPU time (free tier) | 10ms |126| CPU time (paid tier) | 30s (default), 5min (max) |127128See [gotchas.md](./gotchas.md#limits-reference) for complete limits table.129130## Prerequisites131132Before deploying Email Workers:1331341. **Enable Email Routing** in Cloudflare dashboard for your domain1352. **Verify destination addresses** for forwarding1363. **Configure DMARC/SPF** for sending domains (required for replies)1374. **Set up wrangler.jsonc** with SendEmail binding138139See [configuration.md](./configuration.md) for detailed setup.140141## Service Worker Syntax (Deprecated)142143Modern projects should use ES modules format shown above. Service Worker syntax (`addEventListener('email', ...)`) is deprecated but still supported.144145## See Also146147- [Email Routing Documentation](https://developers.cloudflare.com/email-routing/)148- [Workers Platform](https://developers.cloudflare.com/workers/)149- [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/)150- [postal-mime on npm](https://www.npmjs.com/package/postal-mime)151- [mimetext on npm](https://www.npmjs.com/package/mimetext)152