DEV Community

Cover image for How to Configure SPF, DKIM, and DMARC: Stop Your Email From Going to Spam
Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

How to Configure SPF, DKIM, and DMARC: Stop Your Email From Going to Spam

The first time I sent a transactional email from my own server to a Gmail address, it vanished. Not in spam-just gone. I spent a day learning that the modern email stack doesn't care about your SMTP banner or your rDNS. It cares about three DNS records: SPF, DKIM, and DMARC. Get any of them wrong and your mail goes to /dev/null. Get all three right and you're in the inbox. There's no middle ground anymore.

This is the article I wish someone had handed me before I spent a week reading RFCs and Gmail's Postmaster Tools documentation. We'll cover what each record actually does, how to set them up with Postfix + OpenDKIM on Debian, how to read the reports that come back, and how to migrate from a permissive policy to a strict one without nuking your deliverability for a week.

The Three-Layer Model

Email authentication is defense in depth. Each layer catches a different class of abuse.

CodeCopy

Enter fullscreen mode Exit fullscreen mode

┌─────────────────────────────────────────────┐
│ Inbound email arrives │
└────────────────────┬────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────┐
│ SPF check: did the connecting IP belong to a server │
│ the domain owner authorized (in DNS TXT record)? │
└────────────────────┬──────────────────────────────────┘
│ pass / fail / softfail / neutral
▼
┌───────────────────────────────────────────────────────┐
│ DKIM check: was the message signed with a private │
│ key whose public half is in DNS, and is the signature│
│ intact (headers + body hash match)? │
└────────────────────┬──────────────────────────────────┘
│ pass / fail / permfail
▼
┌───────────────────────────────────────────────────────┐
│ DMARC check: do SPF and DKIM align with the From: │
│ domain? What policy applies (none / quarantine / │
│ reject)? Where should we send reports? │
└────────────────────┬──────────────────────────────────┘
│
▼
┌────────────────────┐
│ Delivered or not │
└────────────────────┘

Enter fullscreen mode Exit fullscreen mode

SPF authenticates the envelope. DKIM authenticates the message content. DMARC ties them to the visible From: header and tells the receiver what to do when authentication fails. Without DMARC, attackers can spoof your domain. With DMARC in reject mode, they basically can't.

Why Developers Care

If you self-host email, run a transactional mail server, send a newsletter, or write code that sends email on behalf of users, you need to understand these three records. The major receivers-Gmail, Outlook, Yahoo, Apple-now require DMARC alignment for bulk senders and treat unsigned mail with suspicion. Gmail's February 2024 sender requirements explicitly call out DMARC at p=none minimum for any sender doing more than 5,000 messages a day to Gmail.

If you're sending password resets, magic links, or 2FA codes and they're going to spam, this is almost always why.

Prerequisites

  • A domain you control DNS for.
  • A mail server (Postfix is what I'll use; the principles apply to Exim, Haraka, Mailcow, etc.).
  • Root or sudo on that server.
  • A way to publish TXT records in your DNS (Cloudflare, Route 53, your registrar-doesn't matter).
  • Patience for DNS propagation. SPF takes minutes to propagate; DKIM key rotation needs to overlap, not switch.
  • A test recipient at Gmail, Outlook, and ideally MailTester.com or mail-tester.com.

SPF: Sender Policy Framework

SPF is a TXT record at the apex of your domain that lists which IPs are allowed to send mail from your domain. Receivers do a DNS lookup on yourdomain.com for TXT records starting with v=spf1.

A simple SPF record for a single-server setup:

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
yourdomain.com. IN TXT "v=spf1 ip4:203.0.113.25 -all"

Enter fullscreen mode Exit fullscreen mode


plaintext

The mechanisms:

  • ip4:203.0.113.25 - explicit IPv4
  • ip6:2001:db8::25 - explicit IPv6
  • include:_spf.google.com - include another domain's SPF
  • a - the A record of the current domain
  • mx - the MX records of the current domain
  • exists:%{i}.spf.yourdomain.com - DNS-based macro check (advanced)

The qualifiers:

  • + (default, pass) - explicitly allowed
  • ~ (softfail) - probably not allowed, accept but mark
  • - (fail) - not allowed, reject
  • ? (neutral) - no assertion

A common pattern for a small business using Google Workspace plus a transactional sender:

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
yourdomain.com. IN TXT "v=spf1 include:_spf.google.com include:sendgrid.net ip4:203.0.113.25 ~all"

Enter fullscreen mode Exit fullscreen mode


markdown

End with -all when you're confident, ~all while you're still warming up. End with +all and you've told the world anyone can send from your domain-don't.

The SPF lookup limit. SPF spec says receivers should perform at most 10 DNS lookups (include:, a, mx, redirect, exists: all count). Exceed it and SPF returns permerror and your mail fails. This bites companies that include Sendgrid, Mailgun, Salesforce, Stripe, and three marketing tools. The fix is SPF flattening-resolve the includes once and write a static record. Tools like EasyDMARC's SPF flattener or a DIY script do this, with the trade-off that you now have to re-flatten when an upstream changes their IPs.

DKIM: DomainKeys Identified Mail

DKIM signs the message. The sending mail server has a private key; the public key is published in DNS. The receiver fetches the public key, verifies the signature, and confirms the message wasn't tampered with in transit.

A DKIM record looks like:

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
selector1._domainkey.yourdomain.com. IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc..."

Enter fullscreen mode Exit fullscreen mode


markdown

The selector1 part is the selector. You can have many selectors, which is how you rotate keys without downtime.

Installing OpenDKIM

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo apt install opendkim opendkim-tools

Enter fullscreen mode Exit fullscreen mode


conf

/etc/opendkim.conf:

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


conf
BaseDirectory /var/spool/postfix/opendkim
Socket local:/var/spool/postfix/opendkim/opendkim.sock
UserID opendkim:opendkim
UMask 007
Canonicalization relaxed/relaxed
Mode sv
SubDomains no
AutoRestart yes
AutoRestartRate 10/1M
Background yes
DNSTimeout 5
SignatureAlgorithm rsa-sha256
KeyTable refile:/etc/opendkim/KeyTable
SigningTable refile:/etc/opendkim/SigningTable
ExternalIgnoreList refile:/etc/opendkim/TrustedHosts
InternalHosts refile:/etc/opendkim/TrustedHosts

Enter fullscreen mode Exit fullscreen mode


markdown

Postfix needs to talk to OpenDKIM via a socket. The socket path must be readable by the Postfix user. The cleanest setup is to put the socket inside Postfix's chroot directory.

Generating the Key

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo mkdir -p /etc/opendkim/keys/yourdomain.com
sudo opendkim-genkey -b 2048 -d yourdomain.com -s default -D /etc/opendkim/keys/yourdomain.com
sudo chown -R opendkim:opendkim /etc/opendkim/keys/yourdomain.com
sudo chmod 600 /etc/opendkim/keys/yourdomain.com/default.private

Enter fullscreen mode Exit fullscreen mode


plaintext

This creates default.private (the secret, keep it on the server) and default.txt (the DNS record to publish). The contents of default.txt go into your DNS as a TXT record at default._domainkey.yourdomain.com.

The KeyTable and SigningTable

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


conf

/etc/opendkim/KeyTable

default._domainkey.yourdomain.com yourdomain.com:default:/etc/opendkim/keys/yourdomain.com/default.private

/etc/opendkim/SigningTable

*@yourdomain.com default._domainkey.yourdomain.com

/etc/opendkim/TrustedHosts

127.0.0.1
::1
mail.yourdomain.com
yourdomain.com
203.0.113.25

Enter fullscreen mode Exit fullscreen mode


plaintext

The *@yourdomain.com rule tells OpenDKIM to sign every outbound message from this domain. The TrustedHosts list says "these hosts are allowed to submit mail to be signed"-important so spammers on the same box can't abuse it.

Wiring into Postfix

/etc/postfix/main.cf:

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


conf
milter_default_action = accept
milter_protocol = 6
smtpd_milters = local:/opendkim/opendkim.sock
non_smtpd_milters = local:/opendkim/opendkim.sock

Enter fullscreen mode Exit fullscreen mode


plaintext

/etc/postfix/master.cf should already have the submission service enabled on port 587. OpenDKIM will sign anything Postfix sends out.

Restart everything:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo systemctl restart opendkim postfix

Enter fullscreen mode Exit fullscreen mode


plaintext

Send a test mail:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
echo "test dkim" | mail -s "dkim test" check-auth@verifier.port25.com

Enter fullscreen mode Exit fullscreen mode


markdown

You'll get an automated reply with the authentication results. Look for DKIM check: pass.

DMARC: Tying It Together

DMARC is a TXT record at _dmarc.yourdomain.com. It tells receivers what to do when SPF or DKIM fail and where to send reports.

Plain TextCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
_dmarc.yourdomain.com. IN TXT "v=DMARC1; p=quarantine; rua=mailto:dmarc-reports@yourdomain.com; ruf=mailto:dmarc-failures@yourdomain.com; pct=100; adkim=s; aspf=s"

Enter fullscreen mode Exit fullscreen mode


markdown

The fields:

  • p= policy: none (monitor only), quarantine (spam folder), reject (drop)
  • pct= percentage of mail the policy applies to, 0-100
  • rua= aggregate report destination (daily XML reports)
  • ruf= forensic report destination (per-message failure samples; rarely honored anymore)
  • adkim= DKIM alignment: s strict (From: domain must exactly match d= in DKIM), r relaxed (subdomains ok)
  • aspf= SPF alignment: s strict, r relaxed
  • sp= subdomain policy (defaults to p if omitted)
  • fo= forensic options: 0 (default), 1 (any fail), d (DKIM fail), s (SPF fail)

Alignment is the part everyone misses. DMARC doesn't just check that SPF or DKIM passed. It checks that the domain they passed for matches the From: header. If you send mail from newsletter@yourdomain.com but the SPF is for mailgun.net and DKIM is signed d=mailgun.org, both pass technically but neither aligns, and DMARC fails. That's why third-party senders have to be configured to sign with your domain (often called "authenticated sending" or "dedicated IP").

The Migration Path

Don't go straight to p=reject. You'll bounce mail you didn't know was being sent. The canonical path:

  1. p=none; pct=100; rua=mailto:... - monitor for two weeks
  2. Read the reports. Identify every legitimate sender. Add missing SPF includes.
  3. p=none; pct=100 for another two weeks. Reports should now show no failures from legitimate sources.
  4. p=quarantine; pct=10 - quarantine 10% of failures. Watch the reports.
  5. p=quarantine; pct=50, then pct=100. Wait a week at each step.
  6. p=reject; pct=10, ramp to pct=100.

This takes 4-8 weeks. Skipping it means you'll bounce a marketing email the CEO sent from a third-party tool no one told IT about.

Reading DMARC Reports

Receivers send aggregate reports daily as XML attachments to your rua= address. They're useless raw. Parse them.

parsedmarc is the standard tool:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sudo apt install python3-pip
pip3 install parsedmarc elasticsearch kibana # or skip ES and just get JSON

Enter fullscreen mode Exit fullscreen mode


plaintext

A simpler approach: a Python script that pulls mail from an IMAP folder, parses each XML attachment, and writes JSONL.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

!/usr/bin/env python3

"""Parse DMARC aggregate reports from an IMAP mailbox."""
import imaplib
import email
import xml.etree.ElementTree as ET
import json
import zipfile
import gzip
import io
from pathlib import Path

IMAP_HOST = "imap.yourdomain.com"
IMAP_USER = "dmarc-reports@yourdomain.com"
IMAP_PASS = "..." # use an app-specific password, not your real one

REPORTS_DIR = Path("/var/log/dmarc")
REPORTS_DIR.mkdir(parents=True, exist_ok=True)

def _decompress(payload: bytes, filename: str) -> str:
"""DMARC reports are gzipped or zipped XML."""
if filename.endswith(".gz"):
return gzip.decompress(payload).decode("utf-8", errors="replace")
if filename.endswith(".zip"):
with zipfile.ZipFile(io.BytesIO(payload)) as zf:
with zf.open(zf.namelist()[0]) as fh:
return fh.read().decode("utf-8", errors="replace")
return payload.decode("utf-8", errors="replace")

def _parse_xml(xml_text: str) -> dict:
root = ET.fromstring(xml_text)
metadata = root.find("report_metadata")
policy = root.find("policy_published")
records = []
for rec in root.findall("record"):
row = rec.find("row")
policy_eval = rec.find("auth_results")
records.append({
"source_ip": row.findtext("source_ip"),
"count": int(row.findtext("count") or "0"),
"disposition": row.findtext("policy_evaluated/disposition"),
"dkim_aligned": row.findtext("policy_evaluated/dkim"),
"spf_aligned": row.findtext("policy_evaluated/spf"),
"header_from": policy_eval.findtext("identifiers/header_from"),
"dkim_result": policy_eval.findtext("results/dkim/result"),
"spf_result": policy_eval.findtext("results/spf/result"),
})
return {
"org": metadata.findtext("org_name"),
"report_id": metadata.findtext("report_id"),
"begin": metadata.findtext("date_range/begin"),
"end": metadata.findtext("date_range/end"),
"domain": policy.findtext("domain"),
"policy": policy.findtext("p"),
"records": records,
}

def main() -> None:
client = imaplib.IMAP4_SSL(IMAP_HOST)
client.login(IMAP_USER, IMAP_PASS)
client.select("INBOX")
typ, data = client.search(None, 'SUBJECT', '"Report domain:"')
if typ != "OK":
print("search failed:", data)
return

for num in data[0].split():
typ, msg_data = client.fetch(num, "(RFC822)")
if typ != "OK":
continue
msg = email.message_from_bytes(msg_data[0][1])
for part in msg.walk():
ctype = part.get_content_type()
fname = part.get_filename() or ""
if ctype == "application/gzip" or ctype == "application/zip" or fname.endswith((".gz", ".zip")):
payload = part.get_payload(decode=True)
try:
xml_text = decompress(payload, fname)
parsed = _parse_xml(xml_text)
out = REPORTS_DIR / f"{parsed['org']}
{parsed['report_id']}.json"
out.write_text(json.dumps(parsed, indent=2))
print(f"wrote {out}: {sum(r['count'] for r in parsed['records'])} messages")
except Exception as exc:
print(f"parse failed for {fname}: {exc}")
client.store(num, "+FLAGS", "\Seen")

client.logout()

if name == "main":
main()

Enter fullscreen mode Exit fullscreen mode


markdown

Run it nightly via cron. The output is JSONL you can grep, load into SQLite, or feed to Elasticsearch. The key fields to watch:

  • disposition == "reject" and dkim_aligned == "fail" - someone tried to spoof your domain and DMARC blocked it. Good.
  • disposition == "none" and dkim_aligned == "fail" - mail that failed auth but was still delivered (because p=none). This is your early-warning list of senders to fix before you tighten policy.
  • count summed per source_ip - high counts from IPs you don't recognize = spoofing attempts.

SPF Flattening: When You Hit the 10-Lookup Limit

The 10-lookup limit catches everyone eventually. Here's a minimal Python flattener that resolves includes once and writes a static SPF record. Run it on a schedule; alert if the diff changes.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

!/usr/bin/env python3

"""Flatten SPF includes into a single TXT record. Alert on diff."""
import dns.resolver
import sys

ORIGIN = "yourdomain.com"
WARN_LOOKUPS = 8
MAX_LOOKUPS = 10

seen_lookups = 0
collected_ips: set[str] = set()

def _walk(record: str, domain: str) -> None:
global seen_lookups
parts = record.split()
for token in parts[1:]:
if token == "-all" or token == "~all" or token == "+all" or token == "?all":
continue
mech, _, value = token.partition(":")
if mech == "ip4" or mech == "ip6":
collected_ips.add(token)
elif mech == "include" or mech == "redirect":
seen_lookups += 1
if seen_lookups > MAX_LOOKUPS:
print(f"!! SPF lookup limit exceeded at {value}", file=sys.stderr)
return
try:
answers = dns.resolver.resolve(value, "TXT")
for a in answers:
txt = b"".join(a.strings).decode()
if txt.startswith("v=spf1"):
_walk(txt, value)
except dns.resolver.NoAnswer:
print(f" no TXT for {value}", file=sys.stderr)
elif mech in ("a", "mx"):
seen_lookups += 1
# resolving A/MX records counts toward the limit too
rtype = "A" if mech == "a" else "MX"
try:
target = value or domain
answers = dns.resolver.resolve(target, rtype)
for a in answers:
host = a.to_text().split()[-1] if rtype == "MX" else a.to_text()
collected_ips.add(f"ip4:{host}" if "." in host else f"ip6:{host}")
except dns.resolver.NoAnswer:
pass

def main() -> None:
answers = dns.resolver.resolve(ORIGIN, "TXT")
base_record = ""
for a in answers:
txt = b"".join(a.strings).decode()
if txt.startswith("v=spf1"):
base_record = txt
break
if not base_record:
print(f"no SPF record at {ORIGIN}", file=sys.stderr)
sys.exit(1)

_walk(base_record, ORIGIN)

flat = "v=spf1 " + " ".join(sorted(collected_ips)) + " -all"
print(f"# lookups used: {seen_lookups}")
if seen_lookups > WARN_LOOKUPS:
print(f"!! approaching limit ({seen_lookups}/{MAX_LOOKUPS})", file=sys.stderr)
print(flat)

if name == "main":
main()

Enter fullscreen mode Exit fullscreen mode


plaintext

Caveat: flattening breaks if any included domain uses macros (exists:%{i}...) or redirect= to a dynamic record. Mailgun and Sendgrid publish static IPs, so flattening them is safe. Salesforce and some marketing platforms use dynamic lookups; check before flattening.

Common Mistakes

p=reject on day one. Symptom: legitimate mail starts bouncing. You find out when a customer complains. Fix: start at p=none, read reports for two weeks, ramp slowly.

Forgetting rDNS. Symptom: SPF passes, DKIM passes, DMARC passes, Gmail still throttles you. Fix: your server's IP must have a PTR record that resolves back to a hostname that resolves back to the IP. Set this in your VPS provider's panel; it's not in your DNS.

Multiple SPF records. Symptom: SPF returns permerror. Receivers see two v=spf1 TXT records and bail. Fix: combine into one record. v=spf1 include:_spf.google.com include:sendgrid.net ip4:1.2.3.4 -all, not two separate records.

DKIM body hash mismatch. Symptom: DKIM fails intermittently, especially on forwarded mail. Fix: mailing lists rewrite the body (adding [ListName] to the subject, footers to the body), which breaks DKIM. This is unsolvable at the protocol level-mailing lists must re-sign under their own domain or use ARC.

Publishing DKIM key with wrong selector. Symptom: receiver reports DKIM fail: key not found. Fix: check the selector name matches between your KeyTable, your DNS record label, and the d= and s= tags in your mail headers.

DMARC rua= address bounces. Symptom: receivers stop sending you reports because their reports bounce. Fix: the rua= address must accept mail from external report senders. Don't put it behind aggressive SPF/DMARC checks. Many senders verify the rua= address is reachable before sending.

Forgetting subdomains. Symptom: spoofed mail from phishing.yourdomain.com lands in user inboxes because your DMARC is only on the apex. Fix: explicitly set sp= (subdomain policy) or publish DMARC records on each subdomain.

Troubleshooting with Real Production Examples

"Mail to Gmail lands in spam; mail to Outlook doesn't arrive at all." Gmail is more forgiving but visible; Outlook is brutal and silent. Check authentication at https://www.mail-tester.com. If SPF/DKIM/DMARC all pass, your IP is probably on a reputation blocklist. Check Spamhaus, Barracuda, SORBS. New IPs always start with poor reputation; you have to warm them up by sending low volume to engaged recipients first.

"Gmail's Postmaster Tools shows 0% authenticated." This usually means DMARC isn't aligned. Your From: says newsletter@yourdomain.com but you're sending through Sendgrid with their DKIM signing d=sendgrid.net. Fix: configure Sendgrid to sign with your domain (they call it "authenticated sending" or "dedicated sending"). You publish a CNAME at s1._domainkey.yourdomain.com pointing to s1.domainkey.sendgrid.net, and the alignment works.

"Reports show disposition=reject from IPs I don't recognize." Good news: DMARC is working. Bad news: someone's spoofing your domain. Look at the volume-if it's a few hundred messages a day from random residential IPs, it's a botnet doing a spam run with your domain in the From. If p=reject, they're all blocked. Keep monitoring.

"DKIM fails after Postfix upgrade." The milter socket path changed between Postfix versions on some distros. Check postconf -n | grep milter and ls -la /var/spool/postfix/opendkim/. The socket must be readable by the Postfix user (often postfix:postfix). Restart OpenDKIM, then Postfix.

"Forwarded mail fails DMARC." This is a known protocol limitation. Forwarding rewrites the envelope (the relay's IP isn't in your SPF) but preserves the body and From: header. SPF fails, DKIM might pass, DMARC alignment fails if SPF was the only aligned mechanism. The fix is SRS (Sender Rewriting Scheme), which rewrites the envelope sender so SPF aligns with the forwarding server. Postfix with postsrsd handles this.

Best Practices

  • Use 2048-bit DKIM keys. 1024 is still accepted but considered weak; 2048 is the modern default.
  • Rotate DKIM keys annually. Publish the new selector alongside the old one for two weeks before removing the old.
  • Always end SPF with -all. ~all is fine during warming; +all is a security hole.
  • Send rua= reports to a dedicated mailbox, not your personal one. Volume can be 5-50 MB/day for an active domain.
  • Monitor SPF lookup count. If you're at 8+, you're one new vendor away from breaking.
  • Use strict alignment (adkim=s; aspf=s) on your apex domain. Use relaxed (r) on subdomains if you have many.
  • Keep pct=100 once you're confident in your policy. Lower percentages mean partial enforcement and partial visibility.
  • Test with mail-tester.com before going live with a new sender.

CI/CD Considerations

DNS records are infrastructure; treat them as code. With Terraform and the Cloudflare provider:

hclCopy

Enter fullscreen mode Exit fullscreen mode


terraform

dns/dmarc.tf

resource "cloudflare_record" "dmarc" {
zone_id = var.cloudflare_zone_id
name = "_dmarc"
type = "TXT"
content = "v=DMARC1; p=quarantine; pct=50; rua=mailto:dmarc@${var.domain}; adkim=s; aspf=s"
ttl = 3600
}

resource "cloudflare_record" "spf" {
zone_id = var.cloudflare_zone_id
name = var.domain
type = "TXT"
content = "v=spf1 ip4:${var.mail_ip} include:_spf.google.com -all"
ttl = 3600
}

resource "cloudflare_record" "dkim" {
zone_id = var.cloudflare_zone_id
name = "default._domainkey"
type = "TXT"
content = "v=DKIM1; k=rsa; p=${var.dkim_public_key}"
ttl = 3600
}

Enter fullscreen mode Exit fullscreen mode


plaintext

A pre-merge check script that validates the records resolve correctly before they're applied:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

!/usr/bin/env bash

scripts/validate-dns.sh

set -euo pipefail
DOMAIN="${1:-yourdomain.com}"

SPF must contain v=spf1 and end in -all or ~all

spf=$(dig +short TXT "$DOMAIN" | tr -d '"')
echo "$spf" | grep -q 'v=spf1' || { echo "SPF missing v=spf1"; exit 1; }
echo "$spf" | grep -qE '+?-(all|~all)$' || { echo "SPF doesn't end in -all or ~all"; exit 1; }

DMARC must exist and have p= at minimum

dmarc=$(dig +short TXT "_dmarc.$DOMAIN" | tr -d '"')
echo "$dmarc" | grep -q 'v=DMARC1' || { echo "DMARC missing v=DMARC1"; exit 1; }
echo "$dmarc" | grep -qE 'p=(none|quarantine|reject)' || { echo "DMARC missing p="; exit 1; }

DKIM must exist for the default selector

dkim=$(dig +short TXT "default._domainkey.$DOMAIN" | tr -d '"')
echo "$dkim" | grep -q 'v=DKIM1' || { echo "DKIM missing v=DKIM1"; exit 1; }
echo "$dkim" | grep -q 'k=rsa' || { echo "DKIM missing k=rsa"; exit 1; }

echo "DNS records valid."

Enter fullscreen mode Exit fullscreen mode

Wire this into your CI pipeline as a post-apply step.

Cost Considerations

The protocols themselves are free. The cost is in tools and reputation:

Component Cost Notes
DNS records $0 TXT records cost nothing on any provider
OpenDKIM $0 Open source
Postfix $0 Open source
Parsedmarc $0 Open source
EasyDMARC / dmarcian reporting $20-$100/mo If you don't want to self-host the report parser
SPF flattening service $10-$50/mo If you'd rather not run your own
Warm-up service (Mailwarm, Lemwarm) $30-$100/mo Optional, for new IPs
Postmaster Tools (Gmail, Outlook) $0 Free, but you need to verify your domain

For a self-hosted setup, the only recurring cost is the box itself. For a transactional sender using a third-party SMTP relay (Sendgrid, Postmark, SES), DKIM signing under your domain is included on most plans; SPF flattening is the part that costs money if you have multiple vendors.

Alternatives and Comparison

Tool Strength Weakness Best for
Postfix + OpenDKIM Full control, free You own deliverability Self-hosters, mail operators
Mailcow Dockerized Postfix + DKIM + admin UI Heavier, more moving parts Self-hosters who want a UI
Haraka (Node.js) Plugin architecture, scriptable Less battle-tested for inbound Custom pipelines
Sendgrid / Postmark / SES Managed, high deliverability Costs money, vendor lock-in Transactional senders
Mailgun Good API, EU region Pricing increased in 2024 SaaS apps
Amazon SES Cheapest at scale Harder to set up, IP reputation to manage High-volume senders

For 99% of developers, the right answer is: Postfix + OpenDKIM on a $5 VPS for personal mail, plus SES or Postmark for transactional app mail. Don't run your own inbound mail server unless you want to-it's a maintenance burden that never ends. Outbound only is much easier.

Real-World Use Cases

Self-hosted personal email. A friend runs Postfix + Dovecot + OpenDKIM on a Hetzner box. DMARC at p=reject after a month of monitoring. SPF flattened because of Google + Sendgrid includes. Reports parsed by a cron'd Python script dumping to a static HTML page he checks weekly.

SaaS app sending password resets. The app sends through Postmark with a dedicated sending domain (mail.app.com) that's DMARC-aligned with the From: domain (app.com). Postmark handles the DKIM signing; the app just sets the right From: header. SPF is v=spf1 include:pm.mtasv.net -all. DMARC is p=reject.

Newsletter platform with multiple senders. Each customer gets a subdomain (customer1.yourdomain.com) with its own DKIM key. SPF flattened to include the platform's IP ranges plus the customer's optional custom SMTP. DMARC p=quarantine on subdomains, p=reject on the apex.

University department mail. Central IT publishes SPF/DKIM/DMARC for the apex domain. Each departmental mailing list server has to use SRS or sign under its own subdomain. Departments that ignore this see their mail land in spam after the central DMARC goes to p=reject.

Conclusion

SPF, DKIM, and DMARC are three layers of a defense-in-depth strategy for email authentication. They're not optional anymore. Every receiver of consequence checks them, and getting them wrong means your mail doesn't get delivered. The setup is genuinely fiddly-DNS records, milter sockets, key rotation, report parsing-but it's a one-time cost for years of reliable delivery. Start at p=none, read your reports, ramp slowly, and you'll end up at p=reject without any drama.


Originally published on Mango Developer.

Top comments (0)