A Cloudflare Email Worker that processes incoming emails, cleans and translates them using AI, and forwards them to a webhook endpoint.
This project leverages Cloudflare's Email Routing and Workers platform to create an intelligent email processing pipeline. When emails are received, the worker:
- Parses the raw email content using PostalMime
- Extracts and cleans the email body (removes URLs, formatting, etc.)
- Rewrites/translates the content using AI (Claude 3.5 Haiku via OpenRouter)
- Forwards the processed email data to a webhook URL
- Email Parsing: Uses PostalMime to parse raw email messages
- Content Cleaning: Removes URLs, extra whitespace, and formatting
- AI Processing: Automatically translates non-English emails and cleans up content
- Webhook Integration: Forwards processed emails to any webhook endpoint
- Error Handling: Robust error handling with email rejection on failures
Cloudflare Email Workers allow you to process incoming emails programmatically. Here's how they work:
- Domain Configuration: Configure your domain to use Cloudflare's MX records
- Worker Binding: Bind your worker to handle incoming emails
- Message Processing: The worker receives a
ForwardableEmailMessageobject with email data
exportdefault{asyncemail(message,env,ctx){// Process the incoming email// message.raw contains the raw email data// message.from and message.to contain sender/recipient info},};- Forward:
message.forward(email)- Forward to another email address - Reply:
message.reply(emailMessage)- Send a reply to the sender - Reject:
message.setReject(reason)- Reject the email with a reason
graph TD
A[Incoming Email] --> B[Cloudflare Email Routing]
B --> C[Email Worker]
C --> D[AI Processing]
D --> E[Webhook]
- Cloudflare account with Email Routing enabled
- Domain configured with Cloudflare DNS
- OpenRouter API key for AI processing
- Webhook endpoint to receive processed emails
Configure these environment variables in your Cloudflare Worker:
OPENROUTER_API_KEY: Your OpenRouter API key for AI processingWEBHOOK_URL: The endpoint where processed emails will be sent
Clone this repository
Install dependencies:
npm install
Configure your
wrangler.jsonc:{ "name": "mailhook-worker", "main": "src/index.ts", "compatibility_date": "2024-01-01" }Add your secrets:
npx wrangler secret put OPENROUTER_API_KEY npx wrangler secret put WEBHOOK_URL
Deploy the worker:
npx wrangler deploy
- In the Cloudflare dashboard, navigate to Email Routing
- Add your domain and configure MX records
- Create a destination address or custom route
- Set up an Email Worker route to trigger this worker
postal-mime: Email parsing libraryhtml-to-text: Convert HTML email content to plain text
The worker uses PostalMime to parse the raw email into a structured format:
constemail=awaitPostalMime.parse(message.raw);Extracts the email body, preferring plain text over HTML:
letbody=email.text;if(!body&&email.html){body=convert(email.html,{selectors: [{selector: "a",options: {ignoreHref: true}},{selector: "img",format: "skip"},],});}Removes URLs, extra whitespace, and formatting:
- Strips HTTP/HTTPS links
- Removes empty brackets
- Normalizes whitespace
Sends the cleaned content to Claude 3.5 Haiku for:
- Translation to English (if needed)
- Content cleanup and formatting
- Removal of marketing content, footers, etc.
Forwards the processed email data as JSON:
{"subject": "Email subject","name": "Sender name","email": "sender@example.com","message": "Processed email content","source": "email","reply_to": "reply@example.com","message_id": "unique-message-id","sent_at": "2024-01-01T12:00:00Z"}The worker includes comprehensive error handling:
- Email parsing failures result in rejection
- AI processing errors cause rejection
- Webhook delivery failures cause rejection
- All errors are logged for debugging
Start the development server:
npx wrangler dev --remote
Test with a sample email:
curl -X POST 'http://localhost:8787/cdn-cgi/handler/email' \ --url-query 'from=sender@example.com' \ --url-query 'to=recipient@example.com' \ --header 'Content-Type: application/json' \ --data-raw 'Subject: Test EmailThis is a test email body.'
Monitor your worker's performance and email processing in the Cloudflare dashboard:
- View worker logs and errors
- Monitor email routing analytics
- Track webhook delivery success rates
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
This project is licensed under the MIT License.