1957 words
10 minutes

Cloudflare Email Routing + Worker: Build a Free Domain Email with Catch-all and Bark Push

Cloudflare Email Routing + Worker: Build a Free Domain Email with Catch-all and Bark Push

Scope: The domain is already hosted on Cloudflare, and you only want to receive email (verification codes, replies, archiving); you don't want to buy business email. Sending email requires a separate service such as Resend or SES and is not covered in this article.

About this article: This is compiled from my own actual deployment on one domain, and the Worker code is the version running in production. The domain is uniformly written as example.com in the article, and the receiving endpoint address, Token, and Bark Key have all been replaced with placeholders. Please replace them with your own.

1. What You End Up With

Terminal window
发件人
│
▼
MX:route1/2/3.mx.cloudflare.net
│
▼
Email Routing(catch-all:anything@example.com)
│
▼
Email Worker「mail-inbound」
├─ 成功 → POST 到自己的接收端 /inbound → 存档 + Bark 推送到 iPhone
└─ 失败 → 写进 KV,每 5 分钟重试一次,最多保留 14 天

The whole thing runs within Cloudflare's free tier, with three goals:

  1. Receive email for the entire domain: github@, aws@, and anything@ all come in, with no need to create addresses one by one.
  2. Not lose a single message: If the receiving endpoint restarts or goes down for a few days, emails are stored in KV first and automatically redelivered once it recovers.
  3. Instant phone notifications: New emails are pushed to the iPhone via Bark, showing only the sender, subject, and recipient address.

2. Environment and Preparation

Item Example in This Article Description
Domain example.com DNS must be hosted on Cloudflare
Inbound entry point Cloudflare Email Routing Free, max 25 MiB per email
Processing logic Email Worker mail-inbound Free plan: 100,000 requests per day
Failure fallback Workers KV BACKLOG Free plan: 1,000 writes per day, written only when delivery fails
Receiving endpoint The /inbound endpoint on my own server Any service that can receive HTTP POST works
Push Bark (iOS) Only a Bark Key is needed

3. Enable Email Routing and Switch MX

In the Cloudflare dashboard, go to your domain → Email → Email Routing (in the Chinese interface, "电子邮件 → 电子邮件路由"), and click enable. Cloudflare will automatically add three MX records, one SPF record, and one TXT record used for DKIM signing:

Type Name Content
MX @ route1.mx.cloudflare.net
MX @ route2.mx.cloudflare.net
MX @ route3.mx.cloudflare.net
TXT @ v=spf1 include:_spf.mx.cloudflare.net ~all
TXT cf2024-1._domainkey v=DKIM1; h=sha256; k=rsa; p=… (automatically generated by Cloudflare)
MX, DKIM, and SPF records automatically added by Email Routing
MX, DKIM, and SPF records automatically added by Email Routing

IV. Writing the Email Worker

4.1 Required Bindings

Binding Name Purpose
KV namespace BACKLOG Stores emails that failed delivery
Environment variable RELAY_URL Receiver address, e.g. https://mail.example.com/inbound
Secret INBOUND_TOKEN Bearer Token used for receiver authentication
Cron trigger */5 * * * * Retries the backlog every 5 minutes

If deploying with Wrangler, the configuration looks roughly like this:

wrangler.toml
name = "mail-inbound"
main = "mail-inbound.js"
compatibility_date = "2026-10-01"
[vars]
RELAY_URL = "https://mail.example.com/inbound"
[[kv_namespaces]]
binding = "BACKLOG"
id = "<你的 KV ID>"
[triggers]
crons = ["*/5 * * * *"]

Set the Token separately; don't write it into the config file:

Terminal window
wrangler secret put INBOUND_TOKEN

4.2 Full Code

mail-inbound.js
// mail-inbound: Cloudflare Email Worker
// Incoming mail → POST RELAY_URL; on failure, store in KV (BACKLOG), retry every 5 minutes, and delete after success.
function b64(buf) {
const u = new Uint8Array(buf); let s = "";
for (let i = 0; i < u.length; i += 0x8000) s += String.fromCharCode.apply(null, u.subarray(i, i + 0x8000));
return btoa(s);
}
async function deliver(env, payload) {
for (let i = 0; i < 3; i++) {
try {
const r = await fetch(env.RELAY_URL, {
method: "POST", body: payload,
headers: { "Authorization": "Bearer " + env.INBOUND_TOKEN, "Content-Type": "application/json" },
});
if (r.ok) return true;
if (r.status === 403) return "reject"; // The receiving end is configured to accept only specified addresses
if (r.status === 400 || r.status === 413) return true; // Bad email; retrying is useless
} catch (e) {}
await new Promise(res => setTimeout(res, 1500 * (i + 1)));
}
return false;
}
export default {
async email(message, env, ctx) {
const raw = await new Response(message.raw).arrayBuffer();
const id = crypto.randomUUID();
const payload = JSON.stringify({ id, from: message.from, to: message.to, raw_b64: b64(raw) });
const res = await deliver(env, payload);
if (res === "reject") { message.setReject("Address not accepted"); return; }
if (!res) {
await env.BACKLOG.put("mail:" + Date.now() + ":" + id, payload, { expirationTtl: 14 * 86400 });
}
},
async scheduled(event, env, ctx) {
const list = await env.BACKLOG.list({ prefix: "mail:" });
for (const k of list.keys) {
const p = await env.BACKLOG.get(k.name);
if (!p) continue;
if (await deliver(env, p)) await env.BACKLOG.delete(k.name);
}
},
async fetch() { return new Response("mail-inbound ok"); },
};

4.3 A Few Design Trade-offs

Send the entire raw email as base64; don't parse it inside the Worker. Workers have CPU time limits, and parsing emails with attachments inside a Worker easily times out; handing it off to the receiver and using a mature library (such as Python's email module) is more reliable.

Concatenate base64 in chunks. Passing too many arguments to String.fromCharCode.apply at once blows the stack, so split into 32KB (0x8000) chunks and concatenate them. Calling it directly on an entire large email will throw Maximum call stack size exceeded.

Handle the three failure cases separately:

Receiver returns Worker's handling Reason
403 Call message.setReject() The receiver says "this address doesn't accept mail", so the sender gets a bounce instead of silence
400 / 413 Treat as processed The email itself is malformed or too large; retrying won't help
Network error / 5xx Back off and retry 3 times; if it still fails, write to KV Temporary failure; re-deliver once the receiver recovers

KV backlog expires automatically after 14 days. If the receiver is down for a few days, no emails are lost; once it recovers, Cron re-delivers them on its own. If it's really down for more than two weeks, they're automatically cleared, so nothing piles up indefinitely.

V. Pointing the catch-all Rule to the Worker

Go back to Email Routing → Routing rules, enable Catch-all address, choose the action Send to a Worker, and select mail-inbound. In the Chinese interface, this corresponds to the "Routing rules" tab, and the catch-all rule is displayed as "Catch-all".

Routing rules: "Catch-all" handed to mail-inbound, status active
Routing rules: "Catch-all" handed to mail-inbound, status active

This way, anything@example.com all go to the Worker. Use a different prefix when signing up for different sites (github@, aws@, ...), so if one of them leaks your email, you can tell at a glance.

VI. Receiver and Bark Push

The receiver is a small service on my server. After receiving /inbound, it does three things:

  1. Verify Authorization: Bearer <INBOUND_TOKEN>; if incorrect, return 401 directly;
  2. Decode raw_b64, parse out the sender, subject, body, and attachments, store them in the database, and view them in the backend by recipient address;
  3. Call Bark once to push to the iPhone.

A Bark push is just an HTTP request:

Terminal window
curl -X POST "https://api.day.app/<你的 Bark Key>" \
-H "Content-Type: application/json" \
-d '{"title":"📧 <发件人名称>","body":"<主题>\n→ <收件地址>","group":"mail"}'

I only push three items — "sender, subject, recipient address" — and not the body: first, I don't want the email body showing up on the lock screen; second, pushes have a length limit, so a long body wouldn't be fully visible anyway. The actual result looks like this — the title is the sender's name, and below it are the subject and recipient address:

Bark new email push received on iPhone
Bark new email push received on iPhone

7. Testing

  1. Use any external mailbox (I used QQ Mail) to send an email to test@example.com;
  2. The email appears in Email Routing's Activity Log (「活动日志」 in the Chinese interface) with the result 「已处理」 (Processed), which means it has been handed off to the Worker;
  3. The email appears in the receiving end's admin panel, and your phone simultaneously receives a push like the one in the previous section.
Activity Log: the test email has been handed to the Worker
Activity Log: the test email has been handed to the Worker

8. Limitations

  • Receive only, cannot send. Replying requires a separate sending service, plus SPF and DKIM configured for the sending domain.
  • Email Routing has a per-message limit of 25 MiB; anything larger is rejected outright.
  • The free KV plan allows 1,000 writes per day. Under normal circumstances it barely writes at all, but keep an eye on it if the receiving end is down for a long time and a large volume of mail arrives.

9. Summary

The core of this whole setup is just two things: catch-all hands all mail for the entire domain to the Worker, and the Worker has a proper failure fallback. The former saves you from configuring addresses one by one; the latter guarantees that not a single email is lost when the receiving end restarts or errors out.

If you also have a spare domain and just want a mailbox that can receive verification codes and archive them, this is the cheapest and most controllable approach I've found so far. Feel free to leave a comment if you have questions.

Share Article

If this article helped you, please share it with others!

Cloudflare Email Routing + Worker: Build a Free Domain Email with Catch-all and Bark Push
https://codqor.com/posts/cloudflare-email-routing-worker/
Author
Liam
Published at
Related PostsSmart
1
Resend Email Sending from 0 to Launch: Domain Verification, Sending Relay, and Bounce Monitoring
TechA complete record of moving server notification emails from QQ Mail SMTP to Resend: choosing a new account and domain, DKIM/SPF/DMARC on Cloudflare, a sending API where only one relay holds the key, the gotchas that quota resets at UTC and receiving also consumes quota, Bark alerts for bounces, and protection against duplicate sends. Together with the previous post on Cloudflare receiving, it covers both sending and receiving.
2
My 256MB Router Can’t Run OpenClash, So I Built TinyLane and Open-Sourced It
TechThe Xiaomi AX3000T has only 256 MB of RAM, making OpenClash too much of a strain, so I packaged the sing-box core, a Go daemon, and a mobile panel into a single binary called TinyLane, with my daily readings at about 35 MB for the core and 20–28 MB for the panel. This article explains why I wrote it, what it can do, the memory pitfalls I hit, and how to install it; the project is open-sourced under GPL-3.0.
3
One API for Multiple TTS Providers: OpenAI Standard Parameter Mapping (MOSS Example)
TechWhen creating voiceovers for short videos, I used Edge TTS, Gemini, and MOSS together, each with different parameters. I later added /v1/audio/speech to my AI relay: clients call it using the OpenAI standard format while the gateway maps parameters per provider (for MOSS, just one line: voice→voice_id), and this article covers the parameter comparison table, mapping implementation, usage examples, and pitfalls.
4
Self-Hosting an Astro Blog: Pitfalls with R2 Image Hosting, D1, Caddy, and SEO
Techcodqor.com is itself an Astro static blog: posts are stored in Cloudflare D1, images in R2, pages are served from its own server via Caddy, comments use Turnstile, and there is an English mirror. This article records the build process and pitfalls in real chronological order, including overly long Bing titles, missed noindex directives, a build machine being cooled down, and the remediation approach after AdSense rejected the site for "low-value content."
5
Xiaomi AX3000T Follow-up: OpenClash Primary/Backup Routing, WireGuard Coexistence, and Lag Troubleshooting
TechTwo weeks after flashing OpenWrt on the AX3000T: switching routing from HomeProxy to OpenClash (Meta core) with primary/backup lines, running WireGuard remote management alongside OpenClash, and tracing cross-ocean link lag from 41 KB/s to 7–8 MB/s.
Random PostsRandom

Comments

Leave a comment

Share your thoughts

Shown after review
Leave the name empty to post as “Anonymous”0 / 3000

Comments

Newest first · 5 at a time

Loading comments…

Profile Image of the Author
Liam
Notes on tech, life, and thoughts.
Categories
Tags
Latest Moments
Site Statistics
Posts
21
Categories
4
Tags
72
Total Words
87,292
Running Days
0 days
Last Activity
0 days ago
Table of Contents