# 常见模式
## 1. 允许列表/拒绝列表
typescript
// 允许列表
const allowed = ["
[email protected]", "
[email protected]"];
if (!allowed.includes(message.from)) {
message.setReject("Not allowed");
return;
}
await message.forward("
[email protected]");
## 2. 解析邮件正文
typescript
import PostalMime from 'postal-mime';
export default {
async email(message, env, ctx) {
// 关键:立即消耗流
const raw = await message.raw.arrayBuffer();
const parser = new PostalMime();
const email = await parser.parse(raw);
console.log({
subject: email.subject,
text: email.text,
html: email.html,
from: email.from.address,
attachments: email.attachments.length
});
await message.forward("
[email protected]");
}
} satisfies ExportedHandler;
## 3. 垃圾邮件过滤器
typescript
const score = parseFloat(message.headers.get("x-cf-spamh-score") || "0");
if (score > 5) {
message.setReject("Spam detected");
return;
}
await message.forward("
[email protected]");
## 4. 归档至 R2
typescript
interface Env { R2: R2Bucket; }
export default {
async email(message, env, ctx) {
const raw = await message.raw.arrayBuffer();
const key = `${new Date().toISOString()}-${message.from}.eml`;
await env.R2.put(key, raw, {
httpMetadata: { contentType: "message/rfc822" }
});
await message.forward("
[email protected]");
}
} satisfies ExportedHandler;
## 5. 在 KV 中存储元数据
typescript
import PostalMime from 'postal-mime';
interface Env { KV: KVNamespace; }
export default {
async email(message, env, ctx) {
const raw = await message.raw.arrayBuffer();
const parser = new PostalMime();
const email = await parser.parse(raw);
const metadata = {
from: email.from.address,
subject: email.subject,
timestamp: new Date().toISOString(),
size: raw.byteLength
};
await env.KV.put(`email:${Date.now()}`, JSON.stringify(metadata));
await message.forward("
[email protected]");
}
} satisfies ExportedHandler;
## 6. 基于主题的路由
typescript
export default {
async email(message, env, ctx) {
const subject = message.headers.get("subject")?.toLowerCase() || "";
if (subject.includes("[urgent]")) {
await message.forward("
[email protected]");
} else if (subject.includes("[billing]")) {
await message.forward("
[email protected]");
} else if (subj