需要在cloudflare开启相关功能,脚本中的邮箱地址自行替换
// 邮件转发规则配置
const FORWARD_RULES = [
{
// 张三测试
matches: ['support', 'test'],
forwardTo: 'arch@test.com',
logging: true
},
{
matches: ['root', 'admin'],
forwardTo: 'admin@nodeloc.com',
logging: true
},
];
// 默认转发地址(当没有匹配规则时使用)
const DEFAULT_FORWARD = 'jack@fake.com';
// 日志函数
const logForward = (from, to, subject, rule) => {
console.log(`
Forward email:
From: ${from}
To: ${to}
Subject: ${subject}
Matched Rule: ${rule}
`);
};
export default {
async email(message, env, ctx) {
const to = message.to.toLowerCase();
const from = message.from;
const subject = message.headers.get('subject') || '(no subject)';
try {
// 遍历所有规则
for (const rule of FORWARD_RULES) {
// 检查是否匹配任何关键词
if (rule.matches.some(match => to.includes(match))) {
// 转发邮件
await message.forward(rule.forwardTo);
// 如果启用了日志
if (rule.logging) {
logForward(from, rule.forwardTo, subject, JSON.stringify(rule.matches));
}
return; // 找到匹配规则后退出
}
}
// 如果没有匹配的规则,使用默认转发
await message.forward(DEFAULT_FORWARD);
logForward(from, DEFAULT_FORWARD, subject, 'default rule');
} catch (error) {
// 错误处理
console.error('Email forwarding error:', error);
// 可以选择在发生错误时拒绝邮件
// message.setReject("Failed to process email");
// 或者尝试转发到默认地址
try {
await message.forward(DEFAULT_FORWARD);
logForward(from, DEFAULT_FORWARD, subject, 'error fallback');
} catch (fallbackError) {
console.error('Fallback forwarding failed:', fallbackError);
message.setReject("Failed to process email");
}
}
}
};