21 min read · Business email and cloud

A customer calls to say the quotation you sent landed in the spam folder, even though it was sent from the normal company email. Another common case is that accounting or sales say mail from the ERP system does not reach some recipients. One possible cause is that the company's domain has not yet declared to receivers who may send mail on its behalf, or that some other system is sending in the company's name without the admin knowing it exists.
This article checks this with a real program: a single Node.js script that reads the SPF, DKIM, DMARC and MX records of a domain, and runs it against well-known public domains. You will see real numbers: how many DNS lookups SPF uses, what level the DMARC policy is set to, and how many bits a DKIM key has. After that comes a table for planning the policy upgrade one step at a time, and a small script that summarizes a DMARC report to find senders we forgot. All the code is in the folder examples/spf-dkim-dmarc-company-email and uses plain Node.js 24, with no packages to install.
The example companies in the article (a factory, a shop, an office) are hypothetical, to show the order of work. They are not BT San customer projects, and numbers marked as hypothetical are not real statistics. The results for public domains come from running the real program on 2026-11-21, and DNS can change at any time.
The real problem: anyone can put your domain name in the From field
The basic mail-sending protocol (SMTP) was designed without checking whether the sender has the right to use that domain name. Anyone can set the From field to accounts@yourcompany. The receiver therefore has no way to know whether the mail came from the real company or from someone else. SPF, DKIM and DMARC are three layers added so receivers can check. Every layer works through the DNS records of your domain, so the person who manages DNS has to do the work. The email provider cannot do all of it for you.
Another reason to do this is the receivers' own requirements. According to the Google email sender guidelines, every sender who sends to Gmail must set up at least one of SPF or DKIM. A sender who sends more than 5,000 messages a day to Gmail accounts must set up all of SPF, DKIM and DMARC (the DMARC policy can be none), and the mail must pass DMARC with alignment, per the same document. Other receivers have their own requirements. These requirements can change, so open the provider's latest page before deciding.
How the three layers work
SPF: which servers may send for this domain
SPF (RFC 7208) is a TXT record that starts with v=spf1 and then lists the allowed sending sources, such as ip4:, include:, a, mx, and ends with all plus a qualifier that says how to treat sources not on the list. -all is fail, ~all is softfail, ?all is neutral, and +all allows everyone, which should not be used because it is the same as having no SPF. The receiver compares the IP of the sending server with this list, using the domain in the envelope address (MAIL FROM), not the From field that people see.
A limit that people often do not know about is the DNS lookup ceiling in RFC 7208 section 4.6.4. The receiver must not make more than 10 lookups while evaluating SPF. The mechanisms that count are include, a, mx, ptr, exists and redirect; ip4, ip6 and all do not count. Nested includes keep adding to the count. If it goes over 10, the result is a permerror and the mail may be rejected. The Microsoft documentation describes this the same way. In addition, a domain must have only one SPF record. If it has two, the result is also a permerror.
DKIM: a signature inside the message
DKIM (RFC 6376) has the sending server sign the message headers and body with a private key and put the signature in the DKIM-Signature header, which specifies d= (the signing domain) and s= (the selector). The receiver fetches the public key from DNS at selector._domainkey.domain and verifies the signature. The key record has tags such as k= (key type) and p= (the public key in base64). If p= is empty, that key has been revoked. A domain can have several selectors, which are used to rotate keys or to separate sending systems. According to Google's sender documentation, senders to personal Gmail accounts must use a DKIM key of 1024 bits or longer.
DMARC: tie the check results to the domain people see, and say what to do
DMARC lives at _dmarc.domain as a TXT record starting with v=DMARC1. It has three jobs. One: it requires the mail to pass SPF or DKIM in a way where the domain matches the From field (alignment). Two: it tells the receiver what to do if the mail fails, using p=none, quarantine or reject. Three: it asks for reports to be sent back with rua=. If SPF passes but the domain that passed does not match From, it does not count as passing DMARC.
On the standard: RFC 7489, which has long been cited, has been replaced by RFC 9989 (the DMARC protocol) and RFC 9990 (aggregate reporting), as the RFC Editor page says it obsoletes RFC 7489. The new version removes the pct tag and adds tags such as t, np and psd. But many records in real use still contain pct, so it still has to be read. The example code in this article can read pct, and the sample report follows the format in appendix C of RFC 7489. Real reports from receivers may differ according to the newer version.
Alignment: where SPF passes but DMARC fails
One message involves at least three domains, and DMARC compares two of them with the domain in the From field. This table summarizes who is compared with whom.
| Domain in the message | Where it is | What it is used for | Does DMARC compare it with From? |
|---|---|---|---|
| Header From | The From field the user sees | DMARC's reference point | It is the side being compared against |
| Envelope MAIL FROM | The address used during SMTP delivery (Return-Path) | SPF checks this domain | Yes, it must align with From |
| DKIM d= | In the DKIM-Signature header | DKIM checks the signing domain | Yes, it must align with From |
| Mode | Tag | Meaning | Hypothetical example (From = mail.factory.example) |
|---|---|---|---|
| relaxed (default) | adkim=r, aspf=r | It is enough for the organizational domain to match | d=factory.example counts as aligned |
| strict | adkim=s, aspf=s | The names must be identical, character for character | d=factory.example is not aligned; it must be mail.factory.example |
A situation often seen with external systems is that an ERP system or a mail-sending service uses the provider's domain as the MAIL FROM. SPF passes, but it is the provider's domain, not the company's, so it is not aligned. The fix is to have that system sign DKIM with the company's domain (d=your company's domain), or to set a custom return-path if the provider supports it. The sample report below has one row of this kind.
Example 1: read the records with a program
Suppose a factory (a hypothetical example) uses the main email of one provider, its ERP system sends invoices, and a document scanner sends files by email. Before changing DNS, the administrator wants to know the current state. The program has two parts. The file lib.mjs holds the logic and takes a resolver as a parameter, so the tests can swap in a fake DNS. The file check.mjs is the command-line runner.
The first part is SPF. The key point is counting lookups with one shared counter across the whole tree of includes and redirects. (The RFC extras about void lookups and the expansion of mx into A lookups are not counted in this example, so it is an approximation.)
// ---- 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;
}For DMARC, parseTags splits the tags and then fills in the defaults required by the specification (pct=100, adkim=r, aspf=r). It also produces warnings for weak settings, for example p=none with no rua, which means nothing is blocked and nobody receives reports either.
// ---- 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;
}For DKIM, the key size is estimated by decoding the base64 of p= into DER and letting the node:crypto module read modulusLength. This is more accurate than guessing from the string length. If the key is ed25519, it is reported as 256 bits, based on the size of the raw key.
// ---- 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 ?? "") };
}The runner just calls the functions above and prints the result. The administrator must give the selector, because DNS has no way to ask which selectors a domain has. Providers often use predictable names; for example, Microsoft 365 uses selector1 and 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`);
}Real results from public domains
We ran the program on five public domains: google.com, microsoft.com, and three Thai domains that publish a DMARC policy in DNS. All the data is readable by anyone already. We only put it side by side to show the picture. We are not judging whether any organization has set things up correctly or incorrectly, because each has context we cannot see, and the selectors we tried are only guessable names, so we see only what we found.
== 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: 2The results read as follows. Every domain has exactly one SPF record. The all qualifier differs: some use -all and some use ~all. The number of lookups differs a lot: google.com uses 1, while chula.ac.th uses 9 of 10, which means only 1 lookup is left, and adding another mail-sending service that needs an include could go over the ceiling. The DMARC policies in this group cover all three levels: reject, quarantine and none. Among the domains with none, some have rua and some do not, and the program warns about the latter. For DKIM, both 1024-bit and 2048-bit keys are in use, and google.com has one selector that has been revoked (empty p=), which is the pattern providers use to retire an old key.
The last two lines come from report.mjs and a sample file that we wrote ourselves, which is explained in the DMARC report section below.
Example 2: read a DMARC report to find forgotten senders
When rua= is set, the large receivers send an aggregate report as an XML file, once a day, to the mailbox you specify. The file says which IP sent how many messages in your domain's name, and what the aligned SPF/DKIM results were. Reading this by eye becomes nearly impossible once there are many, so a summarizing helper is needed. Our example uses a sample file we wrote ourselves, structured according to appendix C of RFC 7489. The domains and IPs in the file are values meant for example documents (factory.example and IPs in the ranges 192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24), not anyone's data.
<?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>The script report.mjs adds up the message count per IP, split into pass and fail, counting a message as passing DMARC when dkim or spf in policy_evaluated is pass. It then compares against the list of IPs we know, and what is left are the unknown senders. One thing to note is that in the sample XML, the row for 198.51.100.7 has a raw SPF result of pass for the domain erp-mailer.example, but policy_evaluated is fail because that domain does not align with From. This is the case described above, where the ERP system uses the provider's 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}`);
}The result is in the last part of output.txt above. 192.0.2.10 is a known sender, with 125 messages passing (120 that passed both checks, plus 5 where DKIM passed but SPF failed, which still counts as passing DMARC). 198.51.100.7 failed 35 messages and 203.0.113.99 failed 8. Both are unknown senders. The administrator must ask whether 198.51.100.7 is our ERP system. If it is, fix it to sign DKIM with the company's domain. If it is not and nobody knows it, that is a sign that someone is sending while impersonating the domain, which is what DMARC with reject can eventually block.
If you have to read real reports regularly, we suggest a widely used open-source tool such as parsedmarc on GitHub (domainaware/parsedmarc, licensed under Apache-2.0), which receives reports over IMAP or an API and can forward them into a data viewing system. Our example is kept short only to show the principle.
Example 3: tests that run offline
Code that counts and parses like this can easily break silently. For example, editing a regex might make it miscount one include. So there is a test file that uses a fake DNS in a fixed table and needs no internet. It tests the lookup counter, going over the ceiling, the case of two SPF records, the DMARC warnings, the DKIM key size from a key generated fresh in the test (it must come out as 2048), and the report summary.
// 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"]);
});Three hypothetical examples
A factory whose ERP sends invoices
Hypothetical example: a factory uses the main email of one provider, its ERP system sends invoices out to customers, and a scanner sends files internally. The first thing to do is a survey, and then make sure the ERP signs DKIM with the company's domain. Invoices affect money, so mail that lands in spam or is rejected affects payment collection. This system should pass DMARC before the others, and the result should be checked with reports.
A shop with marketing email
Hypothetical example: a shop uses an external provider's newsletter system. The Microsoft documentation recommends moving services we do not control, such as bulk email, to a subdomain (for example marketing.yourcompany-domain), which separates its reputation from employees' mail and has its own 10-lookup ceiling. The benefit is that if a newsletter is reported as spam, quotation emails from the main domain are not much affected.
An office whose scanner sends alert emails
Hypothetical example: a scanner and a CCTV system send alert emails in the company's noreply name, directly from an IP in the office. These devices often cannot sign DKIM. The options are to add the office's ip4: to SPF (which does not count as a lookup), or to have them send through the main mail server, which signs for them. The caution is that if the office IP changes with the internet provider, SPF must be updated to match.
Lookup budget: calculated from hypothetical numbers
Suppose a company has four includes (main email, ERP, newsletter, scanner), and suppose each include uses 2 lookups in total when nested ones are counted. That gives 4 × 2 = 8 lookups. If one more new service is added that uses 3, the total is 11, over the ceiling of 10. These numbers are hypothetical, to show the way of thinking. For real work, run check.mjs and look directly.
Example records according to provider documentation
The values in the table come from each provider's official documentation (the links are in the references list). They use contoso.com or a hypothetical domain in place of a real domain, and providers may change the values. Before real use, open the latest page and always use the values the provider generates for you in the admin page.
| Provider | SPF (TXT at the domain root) | DKIM |
|---|---|---|
| Google Workspace | v=spf1 include:_spf.google.com ~all | Generate a key in the Admin console, then put the TXT value into DNS (Google's DKIM steps page was not checked in this round) |
| Microsoft 365 | v=spf1 include:spf.protection.outlook.com -all | Two CNAME records, selector1._domainkey and selector2._domainkey, pointing to the targets Microsoft assigns to each domain (the values in the documentation are illustrative; use the values from your own domain) |
| Zoho Mail | v=spf1 include:zoho.com -all (if you use several Zoho services, the documentation shows include:one.zoho.com) | Create a selector and key in the Admin console, then put it as a TXT record at selector._domainkey.domain, then click Verify and enable it |
Observations from the documentation: Microsoft says that for Microsoft 365 domains it recommends -all because it is used together with DKIM and DMARC, and warns that DMARC will not work fully with ~all if the mail has no DKIM signature. Google's example uses ~all, which is an acceptable choice. The two do not contradict each other; they are just different defaults. Microsoft also does not recommend flattening the SPF of Microsoft 365, because the IPs change often.
A step-by-step plan for tightening the DMARC policy
Do not set reject on day one. The safe order is to observe only first, and then gradually let receivers act. This table is a general practice that we summarized from the meaning of the policies in the RFC. It gives no time spans, because that depends on when the reports become clean.
| Step | Example record | Effect on receivers | What to watch |
|---|---|---|---|
| 1 Observe only | v=DMARC1; p=none; rua=mailto:dmarc@your-company-domain | No mail is blocked. Receivers send reports | The list of all source IPs, which are known and which are unknown |
| 2 Fix the real senders | Same as before | Same as before | Known senders that do not pass (forgot an include, did not sign DKIM with the company's domain, not aligned) |
| 3 Partial quarantine | p=quarantine; pct=10 (a hypothetical starting number, increase gradually) | Receivers put some of the failing mail in a suspicious group | People complaining that mail is missing, and the failing mail in reports being only unknown senders |
| 4 Full quarantine | p=quarantine (pct=100) | All failing mail is held as suspicious | New senders added without notice |
| 5 Reject | p=reject | Receivers reject mail that fails | Bounced mail, through continuous reports, and someone responsible when a new system is added |
Before moving up each step, use report.mjs or a tool such as parsedmarc to check that the known senders nearly all pass and that every unknown IP has been followed up. If you have a domain that is never used to send mail, publish v=spf1 -all and DMARC p=reject straight away. Microsoft itself also recommends v=spf1 -all for parked domains.
Forwarding and mailing lists distort the results
- Forwarding: forwarded mail comes from the IP of the forwarding server, which is not in the SPF of the original domain, so SPF often fails after forwarding. DKIM can still pass if the signed headers and body are not modified. So sign DKIM on every system and do not rely on SPF alone.
- Mailing lists: mailing list software often edits the subject or adds a footer, which breaks the original DKIM signature, and the sending IP changes. Mail from a member of a domain with p=reject may be rejected when it passes through the list. Check the reports before moving to reject if the organization has external mailing lists.
- Providers that send on your behalf: a booking or HR system that sends in the company's name must be on the survey list. Otherwise it will be blocked when the policy is tightened.
- Subdomains: if sp= is not set, subdomains use the p= policy of the main domain, and a subdomain that sends mail must have its own SPF (per the Microsoft documentation, the SPF record of the main domain does not cover subdomains).
Common mistakes and a checklist
- Two SPF records: the result is a permerror. Merge them into one record (check.mjs can detect this, and reports more than one SPF record).
- More than 10 lookups from includes: reduce the number of services, move services to a subdomain, or use ip4: if the provider has fixed IPs and the documentation says so (as Microsoft advises), after which someone has to keep track of IP changes.
- A malformed include: for example, a trailing dot on the domain name, = instead of :, or a space after include: (Microsoft gives these as examples of errors).
- Leaving +all or ?all in place: this makes SPF nearly useless.
- DMARC p=none with no rua: it blocks nothing and produces no reports, which is the same as learning nothing.
- Setting reject before surveying senders: real mail from a forgotten system will be lost.
- A DKIM key that is too short: the Google documentation says to use 1024 bits or longer for personal Gmail.
- Forgetting old keys: after rotating a key, delete it or make p= empty, following the provider's procedure.
- List every system that sends mail in the domain's name, with the owner of each system.
- Record the existing SPF, DKIM and DMARC records before changing anything.
- Run check.mjs on the main domain and on the subdomains used for sending, and look at the lookup count and the warnings.
- Enable DKIM on the main email system and on every system that sends on your behalf, and make the d= domain match the company's domain.
- Set DMARC p=none with an rua that someone actually reads.
- Go through the reports until the known senders pass, then deal with the unknown senders.
- Move up to quarantine and reject according to the table above.
- Test sending mail after every change, and assign someone to watch the reports when a new system is added.
If you are going to use it in real work
The code in this article is an example for learning, not a production-grade tool. The limits to know about are these: the lookup count is approximate (it does not count mx expanded into A lookups, or void lookups); it does not evaluate which IP will actually pass or fail; it reads reports with a regex; and it is tested only for what is written. If you will use it as routine work, you should keep reports daily, send an alert when there is a new unknown IP or the lookup count is near the ceiling, and keep a record of who approved each mail-sending system.
Better check results do not mean mail will always reach the inbox, because receivers also look at other factors, such as IP reputation and content. And SPF, DKIM and DMARC do not protect against spoofed email that uses a look-alike domain. But they are the foundation that most receivers already expect.
References
- 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)




