mirror of
https://github.com/dreamhunter2333/cloudflare_temp_email.git
synced 2026-05-19 23:30:25 +08:00
feat: add ENABLE_CHECK_JUNK_MAIL (#469)
This commit is contained in:
44
worker/src/email/check_junk.ts
Normal file
44
worker/src/email/check_junk.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Bindings } from "../types";
|
||||
import { getBooleanValue } from "../utils";
|
||||
import { commonParseMail } from "../common";
|
||||
|
||||
export const check_if_junk_mail = async (
|
||||
env: Bindings, address: string,
|
||||
raw_mail: string, message_id: string | null
|
||||
): Promise<boolean> => {
|
||||
if (!getBooleanValue(env.ENABLE_CHECK_JUNK_MAIL)) {
|
||||
return false;
|
||||
}
|
||||
const parsedEmail = await commonParseMail(raw_mail);
|
||||
if (!parsedEmail?.headers) return false;
|
||||
const headers = parsedEmail.headers;
|
||||
for (const header of headers) {
|
||||
if (!header["key"]) continue;
|
||||
if (!header["value"]) continue;
|
||||
|
||||
// check spf
|
||||
if (header["key"].toLowerCase() == "received-spf"
|
||||
&&
|
||||
!header["value"].toLowerCase().includes("pass")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// check dkim and dmarc
|
||||
if (header["key"].toLowerCase() == "authentication-results") {
|
||||
if (header["value"].toLowerCase().includes("dkim=")
|
||||
&&
|
||||
!header["value"].toLowerCase().includes("dkim=pass")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (header["value"].toLowerCase().includes("dmarc=")
|
||||
&&
|
||||
!header["value"].toLowerCase().includes("dmarc=pass")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { Bindings, HonoCustomType } from "../types";
|
||||
import { auto_reply } from "./auto_reply";
|
||||
import { isBlocked } from "./black_list";
|
||||
import { triggerWebhook } from "../common";
|
||||
import { check_if_junk_mail } from "./check_junk";
|
||||
|
||||
|
||||
async function email(message: ForwardableEmailMessage, env: Bindings, ctx: ExecutionContext) {
|
||||
@@ -15,6 +16,19 @@ async function email(message: ForwardableEmailMessage, env: Bindings, ctx: Execu
|
||||
return;
|
||||
}
|
||||
const rawEmail = await new Response(message.raw).text();
|
||||
|
||||
// check if junk mail
|
||||
try {
|
||||
const is_junk = await check_if_junk_mail(env, message.to, rawEmail, message.headers.get("Message-ID"));
|
||||
if (is_junk) {
|
||||
message.setReject("Junk mail");
|
||||
console.log(`Junk mail from ${message.from} to ${message.to}`);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("check junk mail error", error);
|
||||
}
|
||||
|
||||
const message_id = message.headers.get("Message-ID");
|
||||
// save email
|
||||
const { success } = await env.DB.prepare(
|
||||
|
||||
Reference in New Issue
Block a user