# 电子邮件路由配置
## Wrangler 配置
### 基础 Email Worker
c
// wrangler.jsonc
{
"name": "email-worker",
"main": "src/index.ts",
"compatibility_date": "2025-01-01",
"send_email": [{ "name": "EMAIL" }]
}
typescript
// src/index.ts
export default {
async email(message, env, ctx) {
await message.forward("
[email protected]");
}
} satisfies ExportedHandler;
### 带有存储绑定
c
{
"name": "email-processor",
"send_email": [{ "name": "EMAIL" }],
"kv_namespaces": [{ "binding": "KV", "id": "abc123" }],
"r2_buckets": [{ "binding": "R2", "bucket_name": "emails" }],
"d1_databases": [{ "binding": "DB", "database_id": "def456" }]
}
typescript
interface Env {
EMAIL: SendEmail;
KV: KVNamespace;
R2: R2Bucket;
DB: D1Database;
}
## 本地开发
bash
npx wrangler dev
# 使用 curl 测试
curl -X POST 'http://localhost:8787/__email'
--header 'content-type: message/rfc822'
--data 'From:
[email protected]
To:
[email protected]
Subject: Test
Body'
## 部署
bash
npx wrangler deploy
**连接到电子邮件路由:**
仪表板: Email > Email Routing > [域名] > Settings > Email Workers > 选择 worker
API:
bash
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/settings"
-H "Authorization: Bearer $API_TOKEN"
-d '{"enabled": true, "worker": "email-worker"}'
## DNS (自动创建)
dns
yourdomain.com. IN MX 1 isaac.mx.cloudflare.net.
yourdomain.com. IN MX 2 linda.mx.cloudflare.net.
yourdomain.com. IN MX 3 amir.mx.cloudflare.net.
yourdomain.com. IN TXT "v=spf1 include:_spf.mx.cloudflare.net ~all"
## 密钥与变量
bash
# 密钥 (加密)
npx wrangler secret put API_KEY
# 变量 (明文)
# wrangler.jsonc
{ "vars": { "THRESHOLD": "5.0" } }
typescript
interface Env {
API_KEY: string;
THRESHOLD: string;
}
## TypeScript 设置
bash
npm install --save-dev @cloudflare/workers-types
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"lib": ["ES2022"],
"types": ["@cloudflare/workers-types"],
"moduleResolution": "bundler",
"strict": true
}
}
typescript
import type { ForwardableEmailMessage } from "@cloudflare/workers-types";
export default {
async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext): Promise {
await message.forward("
[email protected]");
}
} sat