21 分钟阅读 · 企业邮箱与云端

客户打电话来说,我们发出的报价单进了垃圾邮件文件夹,而这封邮件明明是用公司邮箱正常发送的。另一种常见情况是,会计或销售部门反映 ERP 系统发出的邮件没有送达部分收件人。一个可能的原因是,公司的域名还没有向收件方声明哪些发件方可以代为发信,或者有其他系统在管理员不知情的情况下以公司名义发信。
本文用真实的程序来检查这件事:一个 Node.js 单文件脚本,读取域名的 SPF、DKIM、DMARC 和 MX 记录,然后拿去对几个众所周知的公开域名运行。你会看到真实的数字,例如 SPF 用了多少次 DNS lookup、DMARC 的策略设在哪一级、DKIM 密钥有多少位。接下来是逐步调整策略的规划表,以及一个汇总 DMARC 报告的小脚本,用来找出我们遗漏的发件方。全部代码都在 examples/spf-dkim-dmarc-company-email 文件夹中,只用 Node.js 24,无需安装任何软件包。
文中的公司示例(工厂、商店、办公室)是为了展示工作顺序而假设的,并非 BT San 客户的项目;标明为假设的数字也不是真实统计。公开域名的检查结果来自 2026年11月21日 实际运行程序所得,而 DNS 随时可能变动。
真实问题:任何人都可以把你的域名填进 From 栏
基础的邮件发送协议(SMTP)在设计时就不检查发件人是否真的有权使用该域名。任何人都可以把 From 栏设成 accounts@你们公司,因此收件方无从得知这封邮件到底来自真正的公司还是别人。SPF、DKIM 和 DMARC 是后来加上的三层机制,让收件方可以进行验证。每一层都通过你域名的 DNS 记录来运作,所以这是负责管理 DNS 的人必须亲自动手的工作,邮件服务提供商无法全部代劳。
另一个必须做的理由是收件方的门槛。根据 Google email sender guidelines 文档,向 Gmail 发信的所有发件方都必须至少设置 SPF 或 DKIM 其中一项;向 Gmail 账号每天发送超过 5,000 封邮件的发件方,必须同时设置 SPF、DKIM 和 DMARC(DMARC 策略可以设为 none),并且邮件必须按同一文档的 alignment 要求通过 DMARC。其他收件方有各自的标准。这些标准会变动,因此在做决定前应先打开服务提供商的最新页面。
三层机制如何运作
SPF:哪些服务器可以代这个域名发信
SPF(RFC 7208)是一条以 v=spf1 开头的 TXT 记录,后面依次列出允许的发送来源,例如 ip4:、include:、a、mx,并以 all 结尾,同时用限定符(qualifier)说明不在列表中的来源应视为什么:-all 是 fail,~all 是 softfail,?all 是 neutral,+all 表示允许所有人,不应使用,因为这等于没有 SPF。收件方拿发信服务器的 IP 与这份列表比对,依据的是 envelope 地址(MAIL FROM)中的域名,而不是人们看到的 From 栏。
人们常常不知道的一个限制是 RFC 7208 第 4.6.4 节规定的 DNS lookup 上限:收件方在评估 SPF 时,lookup 不得超过 10 次。计入次数的有 include、a、mx、ptr、exists 和 redirect,而 ip4、ip6 和 all 不计入。嵌套的 include 会一层层继续累计。如果超过 10 次,结果为 permerror,邮件可能被拒收。Microsoft 的文档也有一致的说明。此外,一个域名只能有一条 SPF 记录;如果有两条,结果同样是 permerror。
DKIM:邮件本身的签名
DKIM(RFC 6376)让发信服务器用私钥对邮件头和正文签名,并把签名放在 DKIM-Signature 头中,其中注明 d=(签名的域名)和 s=(selector)。收件方从 DNS 中名为 selector._domainkey.域名 的记录取得公钥,再验证签名。密钥记录含有 k=(密钥类型)和 p=(base64 格式的公钥)等标签。如果 p= 为空,表示该密钥已被吊销。一个域名可以有多个 selector,因此可用来轮换密钥,或按发信系统区分。根据 Google 的发件方文档,向个人 Gmail 账号发信的发件方必须使用 1024 位或更长的 DKIM 密钥。
DMARC:把验证结果绑定到人们看到的域名,并规定应如何处理
DMARC 位于 _dmarc.域名,是一条以 v=DMARC1 开头的 TXT 记录,有三项职责。第一,规定邮件必须通过 SPF 或 DKIM,且通过验证的域名要与 From 栏一致(alignment)。第二,用 p=none、quarantine 或 reject 告诉收件方,验证不通过时该怎么做。第三,用 rua= 要求收件方回传报告。如果 SPF 通过,但通过验证的域名与 From 不一致,就不算通过 DMARC。
关于标准:长期被引用的 RFC 7489 已被 RFC 9989(DMARC 协议)和 RFC 9990(aggregate reporting)取代,RFC Editor 页面上注明新版 obsoletes RFC 7489。新版去掉了 pct 标签,并新增了 t、np、psd 等标签,但许多正在使用的实际记录仍带有 pct,因此仍需照常读取。本文的示例代码可以读取 pct,示例报告的格式依照 RFC 7489 附录 C,而收件方实际发出的报告可能因新版而有所不同。
Alignment:SPF 通过但 DMARC 不通过的关键
一封邮件至少涉及三个域名,而 DMARC 会拿其中两个与 From 栏的域名比对。下表概括了谁与谁比对。
| 邮件中的域名 | 位于何处 | 用于什么 | DMARC 是否与 From 比对 |
|---|---|---|---|
| Header From | 用户看到的 From 栏 | DMARC 的参照对象 | 是被比对的一方 |
| Envelope MAIL FROM | 通过 SMTP 发送时的地址(Return-Path) | SPF 检查这个域名 | 是,必须与 From align |
| DKIM d= | 在 DKIM-Signature 头中 | DKIM 检查签名的域名 | 是,必须与 From align |
| 模式 | 标签 | 含义 | 假设示例(From = mail.factory.example) |
|---|---|---|---|
| relaxed(默认) | adkim=r, aspf=r | 主域名(organizational domain)一致即可 | d=factory.example 视为 align |
| strict | adkim=s, aspf=s | 必须每个字符都完全相同 | d=factory.example 不 align,必须是 mail.factory.example |
与外部系统打交道时常见的情况是:ERP 系统或邮件发送服务使用服务提供商的域名作为 MAIL FROM,SPF 虽然通过,但通过的是服务提供商的域名而不是公司的域名,所以不 align。解决办法是让该系统用公司的域名对邮件做 DKIM 签名(d=公司域名),或者在服务提供商支持的情况下设置 custom return-path。下面的示例报告中就有这样的一行。
示例 1:用程序读取记录
假设有一家工厂(假设示例)使用某家服务提供商的主邮箱,ERP 系统发送发票,文档扫描仪把文件发到邮箱。在修改 DNS 之前,管理员想先了解当前的状态。程序分为两部分:文件 lib.mjs 存放逻辑,把 resolver 作为参数传入,方便测试时换成模拟的 DNS;check.mjs 则是从命令行启动的入口。
第一部分是 SPF。关键在于 lookup 的统计:在整棵 include 和 redirect 的树中使用同一个计数器(RFC 中关于 void lookup 的补充规定,以及把 mx 展开为 A lookup 的情况,本示例没有计入,属于近似估算)。
// ---- SPF (RFC 7208) ----
const isSpf = (t) => /^v=spf1(\s|$)/i.test(t);
// Terms that cost a DNS lookup: include, a, mx, ptr, exists, redirect (RFC 7208 4.6.4).
export function lookupTerms(record) {
return record.trim().split(/\s+/).slice(1).map((t) => t.replace(/^[+\-~?]/, "")).filter((t) =>
/^(include:|exists:|redirect=|ptr(:|$)|a(:|\/|$)|mx(:|\/|$))/i.test(t));
}
export async function checkSpf(domain, r, state = { lookups: 0, seen: new Set() }, top = true) {
const records = (await r.txt(domain)).filter(isSpf);
if (top && records.length === 0) return { found: false };
if (records.length !== 1) return { found: records.length > 0, records: records.length, lookups: state.lookups, problem: records.length ? "more than one SPF record (permerror)" : "no SPF record" };
const record = records[0];
const out = { found: true, records: 1, record, all: (record.match(/(?:^|\s)([+\-~?]?)all(?=\s|$)/i) || [])[1] };
if (out.all === "") out.all = "+"; // bare "all" means +all
for (const term of lookupTerms(record)) {
state.lookups++;
const m = term.match(/^(?:include:|redirect=)(.+)$/i);
if (m && !state.seen.has(m[1].toLowerCase())) {
state.seen.add(m[1].toLowerCase());
await checkSpf(m[1], r, state, false); // children add to the shared counter
}
}
if (top) { out.lookups = state.lookups; out.overLimit = state.lookups > 10; }
return out;
}DMARC 部分用 parseTags 拆分标签,再按规范补上默认值(pct=100、adkim=r、aspf=r),并对设置偏弱的情况生成警告,例如没有 rua 的 p=none,意味着什么都不拦截,也没有任何人收到报告。
// ---- DMARC (RFC 7489) ----
export async function checkDmarc(domain, r) {
const rec = (await r.txt("_dmarc." + domain)).filter((t) => /^v=DMARC1\s*;/i.test(t));
if (rec.length === 0) return { found: false, warnings: ["no DMARC record"] };
const t = parseTags(rec[0]);
const d = { found: true, record: rec[0], p: t.p, sp: t.sp, pct: t.pct ?? "100", rua: t.rua, ruf: t.ruf, adkim: t.adkim ?? "r", aspf: t.aspf ?? "r", warnings: [] };
if (rec.length > 1) d.warnings.push("more than one DMARC record");
if (!["none", "quarantine", "reject"].includes(d.p)) d.warnings.push("p= missing or invalid");
if (d.p === "none" && !d.rua) d.warnings.push("p=none without rua: monitoring only and nobody gets the reports");
if (d.p === "none" && d.rua) d.warnings.push("p=none: monitoring only, nothing is blocked yet");
if (d.p !== "none" && Number(d.pct) < 100) d.warnings.push(`pct=${d.pct}: policy applies to a sample only`);
if (!d.rua && d.p !== "none") d.warnings.push("no rua= (no aggregate reports)");
return d;
}DKIM 部分通过把 p= 的 base64 解码成 DER,再让 node:crypto 模块读取 modulusLength 来估算密钥大小,这比从字符串长度猜测更准确;如果密钥是 ed25519,则按原始密钥大小报告为 256 位。
// ---- DKIM (RFC 6376) ----
export function keyBits(tags) {
if (!tags.p) return null;
const der = Buffer.from(tags.p.replace(/\s+/g, ""), "base64");
if ((tags.k ?? "rsa").toLowerCase() === "ed25519") return 256; // raw 32-byte key
try { return createPublicKey({ key: der, format: "der", type: "spki" }).asymmetricKeyDetails.modulusLength; }
catch { return null; } // not a valid SPKI key
}
export async function checkDkim(domain, selector, r) {
const rec = (await r.txt(`${selector}._domainkey.${domain}`)).filter((t) => /(^|;)\s*p=/i.test(t));
if (rec.length === 0) return { selector, found: false };
const t = parseTags(rec[0]);
return { selector, found: true, k: t.k ?? "rsa", revoked: t.p === "", bits: keyBits(t), testing: /(^|:)y(:|$)/.test(t.t ?? "") };
}入口程序只是调用上面的函数并打印结果。管理员必须自己指定 selector,因为 DNS 没有办法查询某个域名有哪些 selector。服务提供商通常使用可预期的名称,例如 Microsoft 365 使用 selector1 和 selector2。
// Usage: node check.mjs <domain> [selector ...]
import { realResolver as r, checkSpf, checkDmarc, checkDkim } from "./lib.mjs";
const [domain, ...selectors] = process.argv.slice(2);
if (!domain) { console.error("usage: node check.mjs <domain> [selector ...]"); process.exit(2); }
console.log(`== ${domain}`);
const mx = await r.mx(domain);
console.log("MX:", mx.length ? mx.map((m) => `${m.priority} ${m.exchange}`).join(", ") : "(none)");
const spf = await checkSpf(domain, r);
if (!spf.found) console.log("SPF: not found");
else {
console.log(`SPF: records=${spf.records} all=${spf.all ? spf.all + "all" : "(none)"} lookups=${spf.lookups}/10${spf.overLimit ? " OVER LIMIT (permerror)" : ""}`);
if (spf.problem) console.log(" problem:", spf.problem);
}
const dmarc = await checkDmarc(domain, r);
if (!dmarc.found) console.log("DMARC: not found");
else {
console.log(`DMARC: p=${dmarc.p} sp=${dmarc.sp ?? "-"} pct=${dmarc.pct} adkim=${dmarc.adkim} aspf=${dmarc.aspf} rua=${dmarc.rua ? "yes" : "no"} ruf=${dmarc.ruf ? "yes" : "no"}`);
}
for (const w of dmarc.warnings) console.log(" warn:", w);
for (const s of selectors) {
const k = await checkDkim(domain, s, r);
console.log(k.found
? `DKIM ${s}: k=${k.k} ${k.revoked ? "REVOKED (p= empty)" : `~${k.bits} bits`}${k.testing ? " (testing flag)" : ""}`
: `DKIM ${s}: not found`);
}公开域名的真实结果
我们用程序检查了五个公开域名:google.com、microsoft.com,以及三个在 DNS 中公布了 DMARC 策略的泰国域名。这些数据本来就任何人都能读取,我们只是拿来对比,让大家有个直观印象,并不评判哪个组织的设置是对是错,因为每个组织都有我们看不到的背景,而且所试的 selector 只是猜测的常见名称,所以只能看到找得到的部分。
== google.com
MX: 10 smtp.google.com
SPF: records=1 all=~all lookups=1/10
DMARC: p=reject sp=- pct=100 adkim=r aspf=r rua=yes ruf=no
DKIM google: not found
DKIM 20230601: k=rsa REVOKED (p= empty)
== microsoft.com
MX: 10 microsoft-com.mail.protection.outlook.com
SPF: records=1 all=-all lookups=6/10
DMARC: p=reject sp=- pct=100 adkim=r aspf=r rua=yes ruf=yes
DKIM selector1: not found
DKIM selector2: k=rsa ~1024 bits
== kasikornbank.com
MX: 5 kasikornbank-com.mail.protection.outlook.com
SPF: records=1 all=-all lookups=2/10
DMARC: p=reject sp=- pct=100 adkim=r aspf=r rua=yes ruf=yes
DKIM selector1: k=rsa ~2048 bits
DKIM selector2: k=rsa ~2048 bits
== chula.ac.th
MX: 20 mail2-gw1.it.chula.ac.th, 100 mail-gw1.it.chula.ac.th
SPF: records=1 all=-all lookups=9/10
DMARC: p=quarantine sp=- pct=100 adkim=r aspf=r rua=yes ruf=yes
DKIM google: k=rsa ~1024 bits
DKIM s1: k=rsa ~2048 bits
== thaipbs.or.th
MX: 10 mx1.hc112-45.ap.iphmx.com, 10 mx2.hc112-45.ap.iphmx.com, 20 thaipbs-or-th.mail.protection.outlook.com
SPF: records=1 all=~all lookups=3/10
DMARC: p=none sp=- pct=100 adkim=r aspf=r rua=no ruf=no
warn: p=none without rua: monitoring only and nobody gets the reports
DKIM selector1: k=rsa ~1024 bits
DKIM selector2: not found
== sample-report.xml (known sender: 192.0.2.10)
192.0.2.10 pass= 125 fail= 0 known
198.51.100.7 pass= 0 fail= 35 UNKNOWN sender
203.0.113.99 pass= 0 fail= 8 UNKNOWN sender
unknown senders: 2结果解读如下:每个域名都只有一条 SPF 记录;all 限定符各不相同,有的用 -all,有的用 ~all。lookup 次数差异很大:google.com 用了 1 次,而 chula.ac.th 用了 9 次(上限 10 次),意味着只剩 1 次的余地,如果再添加一个需要 include 的邮件发送服务,就可能超出上限。这组域名的 DMARC 策略三个级别都有,即 reject、quarantine 和 none,而设为 none 的域名既有带 rua 的,也有不带 rua 的,对后者程序会给出警告。在 DKIM 方面可以看到,1024 位和 2048 位的密钥都在使用,而且 google.com 有一个 selector 已被吊销(p= 为空),这是服务提供商用来停用旧密钥的做法。
最后两行来自 report.mjs 和我们自己编写的示例文件,将在下面的 DMARC 报告一节中说明。
示例 2:读取 DMARC 报告,找出被遗忘的发件方
设置 rua= 之后,大型收件方会每天向指定的邮箱发送一份汇总报告(aggregate report),格式为 XML 文件。文件中说明哪个 IP 以你的域名发了多少封邮件,以及 SPF/DKIM 的 align 结果如何。报告一多,肉眼几乎无法阅读,所以需要有汇总工具。我们的示例使用自己编写的示例文件,其结构依照 RFC 7489 附录 C;文件中的域名和 IP 是文档示例专用的值(factory.example,以及 192.0.2.0/24、198.51.100.0/24、203.0.113.0/24 范围内的 IP),不属于任何人的数据。
<?xml version="1.0" encoding="UTF-8" ?>
<!-- MADE-UP sample shaped like RFC 7489 Appendix C. Domain and IPs are documentation examples. -->
<feedback>
<report_metadata>
<org_name>receiver.example</org_name>
<email>[email protected]</email>
<report_id>made-up-0001</report_id>
<date_range><begin>1700000000</begin><end>1700086399</end></date_range>
</report_metadata>
<policy_published>
<domain>factory.example</domain>
<adkim>r</adkim><aspf>r</aspf><p>none</p><pct>100</pct>
</policy_published>
<record>
<row><source_ip>192.0.2.10</source_ip><count>120</count>
<policy_evaluated><disposition>none</disposition><dkim>pass</dkim><spf>pass</spf></policy_evaluated></row>
<identifiers><header_from>factory.example</header_from></identifiers>
<auth_results><dkim><domain>factory.example</domain><result>pass</result></dkim>
<spf><domain>factory.example</domain><result>pass</result></spf></auth_results>
</record>
<record>
<row><source_ip>198.51.100.7</source_ip><count>35</count>
<policy_evaluated><disposition>none</disposition><dkim>fail</dkim><spf>fail</spf></policy_evaluated></row>
<identifiers><header_from>factory.example</header_from></identifiers>
<auth_results><spf><domain>erp-mailer.example</domain><result>pass</result></spf></auth_results>
</record>
<record>
<row><source_ip>203.0.113.99</source_ip><count>8</count>
<policy_evaluated><disposition>none</disposition><dkim>fail</dkim><spf>fail</spf></policy_evaluated></row>
<identifiers><header_from>factory.example</header_from></identifiers>
<auth_results><spf><domain>factory.example</domain><result>fail</result></spf></auth_results>
</record>
<record>
<row><source_ip>192.0.2.10</source_ip><count>5</count>
<policy_evaluated><disposition>none</disposition><dkim>pass</dkim><spf>fail</spf></policy_evaluated></row>
<identifiers><header_from>factory.example</header_from></identifiers>
<auth_results><dkim><domain>factory.example</domain><result>pass</result></dkim></auth_results>
</record>
</feedback>脚本 report.mjs 按 IP 汇总邮件数量,分为通过和未通过,判断 DMARC 通过的依据是 policy_evaluated 中的 dkim 或 spf 为 pass;然后与我们已知的 IP 列表比对,剩下的就是未知发件方。值得注意的是,在示例 XML 中,198.51.100.7 那一行的原始 SPF 结果对 erp-mailer.example 域名是 pass,但 policy_evaluated 是 fail,因为该域名与 From 不 align。这就是前面提到的 ERP 系统使用服务提供商 MAIL FROM 的情况。
// Sum DMARC results per source IP from an aggregate report and flag unknown senders.
// Usage: node report.mjs <report.xml> [known-ip ...]
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
// A record counts as DMARC-pass when either aligned check (dkim / spf in policy_evaluated) passes.
// simplified: regex parsing is enough for the fixed report shape; use a real XML parser for production.
export function summarize(xml) {
const perIp = new Map();
for (const [, rec] of xml.matchAll(/<record>([\s\S]*?)<\/record>/g)) {
const get = (tag) => rec.match(new RegExp(`<${tag}>([^<]*)</${tag}>`))?.[1];
const ip = get("source_ip"), n = Number(get("count"));
const pe = rec.match(/<policy_evaluated>([\s\S]*?)<\/policy_evaluated>/)[1];
const pass = /<dkim>pass</.test(pe) || /<spf>pass</.test(pe);
const row = perIp.get(ip) ?? { pass: 0, fail: 0 };
row[pass ? "pass" : "fail"] += n;
perIp.set(ip, row);
}
return perIp;
}
export function flagUnknown(perIp, known) {
return [...perIp].filter(([ip]) => !known.includes(ip)).map(([ip]) => ip);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [file, ...known] = process.argv.slice(2);
const perIp = summarize(readFileSync(file, "utf8"));
const unknown = flagUnknown(perIp, known);
for (const [ip, { pass, fail }] of perIp)
console.log(`${ip.padEnd(15)} pass=${String(pass).padStart(4)} fail=${String(fail).padStart(4)} ${known.includes(ip) ? "known" : "UNKNOWN sender"}`);
console.log(`unknown senders: ${unknown.length}`);
}结果见上面 output.txt 的末尾:192.0.2.10 是已知发件方,通过 125 封(120 封两项都通过,加上 5 封 DKIM 通过但 SPF 未通过,这仍算通过 DMARC)。而 198.51.100.7 未通过 35 封,203.0.113.99 未通过 8 封,两者都是未知发件方。管理员需要去询问 198.51.100.7 是否是我们的 ERP 系统;如果是,就改为用公司域名做 DKIM 签名;如果不是,而且没人认识它,就说明有人在冒用域名发信,而这正是 DMARC 设为 reject 最终能够拦住的。
如果需要定期阅读真实的报告,建议使用广泛使用的开源工具,例如 GitHub 上的 parsedmarc(domainaware/parsedmarc,采用 Apache-2.0 许可证),它通过 IMAP 或 API 接收报告,再转发到数据查看系统。我们的示例写得很短,只是为了展示原理。
示例 3:可离线运行的测试
这类做计数和拆分的代码很容易悄悄出错,例如修改 regex 后把 include 多数了一个。因此有一个测试文件,用固定表格的模拟 DNS,无需联网,测试 lookup 计数器、超过上限、有两条 SPF 记录的情况、DMARC 的警告、用测试中现场生成的密钥来检查 DKIM 密钥大小(必须得到 2048),以及报告汇总。
// Offline self-check: node --test test.mjs (DNS is replaced by a fixed table)
import test from "node:test";
import assert from "node:assert/strict";
import { generateKeyPairSync } from "node:crypto";
import { readFileSync } from "node:fs";
import { checkSpf, checkDmarc, checkDkim, lookupTerms } from "./lib.mjs";
import { summarize, flagUnknown } from "./report.mjs";
const zone = (t) => ({ txt: async (n) => t[n] ?? [], mx: async () => [] });
test("SPF: counts lookups through includes, ignores ip4/all, reads qualifier", async () => {
const r = zone({
"a.example": ["v=spf1 include:b.example mx a:mail.a.example ip4:192.0.2.0/24 ~all"], // 3 terms
"b.example": ["v=spf1 include:c.example exists:%{i}.x.example -all"], // +2
"c.example": ["v=spf1 ptr ip6:2001:db8::/32 -all"], // +1
});
const s = await checkSpf("a.example", r);
assert.equal(s.lookups, 6);
assert.equal(s.all, "~");
assert.equal(s.overLimit, false);
assert.deepEqual(lookupTerms("v=spf1 ip4:1.2.3.4 -all"), []);
});
test("SPF: 11 lookups is over the limit; two records is a problem", async () => {
const many = "v=spf1 " + Array.from({ length: 11 }, (_, i) => `include:i${i}.example`).join(" ") + " -all";
assert.equal((await checkSpf("a.example", zone({ "a.example": [many] }))).overLimit, true);
const two = await checkSpf("a.example", zone({ "a.example": ["v=spf1 -all", "v=spf1 +all"] }));
assert.match(two.problem, /more than one/);
});
test("DMARC: tags and weak-setup warnings", async () => {
const weak = await checkDmarc("a.example", zone({ "_dmarc.a.example": ["v=DMARC1; p=none"] }));
assert.equal(weak.pct, "100");
assert.ok(weak.warnings.some((w) => w.includes("without rua")));
const ok = await checkDmarc("a.example", zone({ "_dmarc.a.example": ["v=DMARC1; p=quarantine; pct=25; rua=mailto:[email protected]; adkim=s"] }));
assert.equal(ok.adkim, "s");
assert.ok(ok.warnings.some((w) => w.includes("pct=25")));
assert.equal((await checkDmarc("none.example", zone({}))).found, false);
});
test("DKIM: key size from a real generated key, revoked key", async () => {
const { publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
const p = publicKey.export({ type: "spki", format: "der" }).toString("base64");
const r = zone({ "s1._domainkey.a.example": [`v=DKIM1; k=rsa; p=${p}`], "old._domainkey.a.example": ["v=DKIM1; p="] });
assert.equal((await checkDkim("a.example", "s1", r)).bits, 2048);
assert.equal((await checkDkim("a.example", "old", r)).revoked, true);
assert.equal((await checkDkim("a.example", "nope", r)).found, false);
});
test("Report: sums per IP and flags unknown senders", () => {
const m = summarize(readFileSync(new URL("./sample-report.xml", import.meta.url), "utf8"));
assert.deepEqual(m.get("192.0.2.10"), { pass: 125, fail: 0 }); // 120 + 5 (dkim pass, spf fail still passes DMARC)
assert.deepEqual(m.get("203.0.113.99"), { pass: 0, fail: 8 });
assert.deepEqual(flagUnknown(m, ["192.0.2.10"]), ["198.51.100.7", "203.0.113.99"]);
});三种假设情景
ERP 发送发票的工厂
假设示例:工厂使用某家服务提供商的主邮箱,ERP 系统把发票发给客户,扫描仪发送内部文件。首先要做的是盘点,然后检查并让 ERP 用公司域名做 DKIM 签名。发票关系到钱,邮件进垃圾邮箱或被拒收就会影响收款,所以应让这个系统先于其他系统通过 DMARC,并用报告检查结果。
有营销邮件的商店
假设示例:商店使用外部服务提供商的电子报发送系统。Microsoft 文档建议把我们无法控制的服务(例如群发邮件 bulk email)移到子域名上(例如 marketing.公司域名),这样可以把声誉与员工邮件分开,并拥有自己的 10 次 lookup 上限。好处是,如果电子报被举报为垃圾邮件,主域名发出的报价邮件不会受到太大连带影响。
用扫描仪发送告警邮件的办公室
假设示例:扫描仪和监控摄像头以公司的 noreply 名义,直接从办公室的 IP 发送告警邮件。这类设备通常无法做 DKIM 签名。可选的做法是在 SPF 中加入办公室的 ip4:(不计入 lookup),或者让它们通过会代为签名的主邮件服务器发送。需要注意的是,如果办公室的 IP 随互联网服务提供商而变,就必须相应更新 SPF。
lookup 预算:用假设的数字计算
假设某公司有四个 include(主邮箱、ERP、电子报、扫描仪),并假设每个 include 在嵌套计算时合计使用 2 次 lookup,则共计 4 × 2 = 8 次 lookup。如果再增加一个会用到 3 次的新服务,就会变成 11 次,超过 10 次的上限。这个数字是为了展示思路而假设的,真实情况请直接运行 check.mjs 查看。
按服务提供商文档给出的记录示例
表中的值来自各家的官方文档(链接见参考资料列表),以 contoso.com 或假设的域名代替真实域名,而且服务提供商可能会更改这些值。实际使用前,务必打开最新页面,并始终使用服务提供商在管理员页面为你生成的值。
| 服务提供商 | SPF(域名根部的 TXT) | DKIM |
|---|---|---|
| Google Workspace | v=spf1 include:_spf.google.com ~all | 在 Admin console 页面生成密钥,再把 TXT 值放进 DNS(本轮尚未核对 Google 的 DKIM 步骤页面) |
| Microsoft 365 | v=spf1 include:spf.protection.outlook.com -all | 两条 CNAME:selector1._domainkey 和 selector2._domainkey,指向 Microsoft 为每个域名指定的目标(文档中的值仅为示意,请使用你自己域名的值) |
| Zoho Mail | v=spf1 include:zoho.com -all(如果使用 Zoho 的多项服务,文档显示为 include:one.zoho.com) | 在 Admin console 中创建 selector 和密钥,再作为 TXT 放在 selector._domainkey.域名,然后点击 Verify 并启用 |
文档中的观察:Microsoft 指出,对于 Microsoft 365 域名建议使用 -all,因为它与 DKIM 和 DMARC 配合使用,并提醒如果邮件没有 DKIM 签名,DMARC 搭配 ~all 就无法充分发挥作用。而 Google 的示例使用 ~all,这也是可接受的选择。两者并不矛盾,只是默认值不同。另外,Microsoft 不建议对 Microsoft 365 的 SPF 做 flatten,因为 IP 经常变动。
逐步调整 DMARC 策略的规划
不要在第一天就设成 reject。比较安全的顺序是:先只观察,再逐步让收件方采取行动。下表是我们根据 RFC 中各策略的含义归纳的通用做法,没有规定具体时长,因为这取决于报告什么时候变得干净。
| 步骤 | 示例记录 | 对收件方的影响 | 需要查看什么 |
|---|---|---|---|
| 1 只观察 | v=DMARC1; p=none; rua=mailto:dmarc@公司域名 | 不拦截邮件,收件方会发送报告 | 所有来源 IP 的列表:哪些认识,哪些不认识 |
| 2 修正真实的发件方 | 同上 | 同上 | 已知但未通过的发件方(忘了 include、没有用公司域名做 DKIM 签名、没有 align) |
| 3 部分 quarantine | p=quarantine; pct=10(起始数字为假设,再逐步提高) | 收件方把一部分未通过的邮件放入可疑邮件分组 | 有没有人抱怨邮件丢失;报告中未通过的邮件是否只剩未知发件方 |
| 4 完整 quarantine | p=quarantine (pct=100) | 所有未通过的邮件都被拦下归为可疑 | 未经通知就新增的发件方 |
| 5 reject | p=reject | 收件方拒收未通过的邮件 | 退回的邮件(bounce);通过报告持续观察,并有人负责在新增系统时跟进 |
在推进每一步之前,先用 report.mjs 或 parsedmarc 这类工具查看:已知发件方是否几乎全部通过,未知 IP 的列表是否都已追查清楚。如果有完全不用来发邮件的域名,就直接发布 v=spf1 -all 和 DMARC p=reject。Microsoft 也建议对闲置域名(parked domain)使用 v=spf1 -all。
邮件转发和邮件列表会让结果失真
- 转发(forwarding):被转发的邮件会来自转发服务器的 IP,而这个 IP 不在原始域名的 SPF 中,所以转发后 SPF 通常不通过。而 DKIM 只要签名的邮件头和正文没有被修改,仍然可以通过,因此应让每个系统都做 DKIM 签名,不要只依赖 SPF。
- 邮件列表:邮件列表软件常常修改主题或在邮件末尾加内容,导致原有的 DKIM 签名失效,发送的 IP 也随之改变。设为 p=reject 的域名,其成员发出的邮件经过邮件列表后可能被拒收。如果组织有外部邮件列表,应在升级为 reject 之前先查看报告。
- 代发的服务提供商:以公司名义发信的预订系统或 HR 系统必须列入盘点清单,否则在提升策略时会被拦下。
- 子域名:如果不设置 sp=,子域名沿用主域名的 p= 策略;而发信的子域名必须有自己的 SPF(根据 Microsoft 的文档,主域名的 SPF 记录不涵盖子域名)。
常见错误与检查清单
- 有两条 SPF 记录:结果为 permerror,应合并为一条(可用 check.mjs 检查,它会提示 more than one SPF record)
- include 超过 10 次 lookup:减少服务数量、把服务移到子域名,或者在服务提供商有固定 IP 且文档有注明时改用 ip4:(如 Microsoft 所建议的),但之后需要有人跟踪 IP 的变化
- include 写错格式:例如在域名末尾加了句点、用 = 代替 :,或在 include: 后面留了空格(Microsoft 把它列为错误示例)
- 把 +all 或 ?all 一直留着:会让 SPF 几乎失去作用
- 没有 rua 的 DMARC p=none:既不拦截也没有报告,等于什么都没学到
- 在盘点发件方之前就设成 reject:被遗忘的系统发出的真实邮件会丢失
- DKIM 密钥太短:Google 文档规定个人 Gmail 要使用 1024 位或更长
- 忘了旧密钥:轮换密钥之后,应按服务提供商的步骤删除旧密钥或把 p= 设为空
- 列出所有以域名名义发信的系统,并注明各系统的负责人
- 修改之前,先记录原有的 SPF、DKIM、DMARC 记录
- 对主域名和用来发信的子域名运行 check.mjs,查看 lookup 次数和警告
- 在主邮件系统以及所有代发信的系统中启用 DKIM,并让 d= 域名与公司域名一致
- 设置 DMARC p=none,并配上真正有人阅读的 rua 邮箱
- 逐步查看报告,直到已知发件方都通过,再处理未知发件方
- 按上表升级为 quarantine 和 reject
- 每次修改后都测试发信,并在新增系统时指定专人查看报告
如果要实际应用
本文的代码是学习用的示例,不是 production 级别的工具。需要了解的限制有:lookup 的统计是近似的(没有计入展开为 A lookup 的 mx,也没有计入 void lookup),不评估哪个 IP 实际会通过或不通过,用 regex 读取报告,而且只测试了已编写的部分。如果要当作日常工作使用,应当按天保存报告,在出现未知的新 IP 或 lookup 次数接近上限时发出提醒,并记录每个邮件发送系统由谁批准。
检查结果变好并不意味着邮件一定会进入 inbox,因为收件方还会考虑其他因素,例如 IP 的声誉和内容;而且 SPF、DKIM、DMARC 也无法防止使用外观相似域名的钓鱼邮件。但它们是大多数收件方已经期待的基础。
参考资料
- RFC 7208: Sender Policy Framework (SPF) (accessed 2026-11-21)
- RFC 6376: DomainKeys Identified Mail (DKIM) Signatures (accessed 2026-11-21)
- RFC 7489: DMARC (obsoleted by RFC 9989) (accessed 2026-11-21)
- RFC 9989: DMARC Protocol (accessed 2026-11-21)
- Google: Email sender guidelines (accessed 2026-11-21)
- Google Workspace: Set up SPF (accessed 2026-11-21)
- Microsoft: Set up SPF to help prevent spoofing (accessed 2026-11-21)
- Microsoft: Use DKIM for email in your custom domain (accessed 2026-11-21)
- Zoho Mail: SPF configuration (accessed 2026-11-21)
- Zoho Mail: DKIM configuration (accessed 2026-11-21)




