How to set up SPF, DKIM and DMARC for a company domain, step by step
You write one SPF record and count its DNS lookups, generate a DKIM key with openssl and turn it into a TXT record, then publish DMARC with reports and tighten the policy from p=none to p=reject. We ran every command, and the dig output comes from real domains and from a local test zone.
The receiving server checks three things. Whether the message left a server the domain allows to send mail (SPF). Whether the signature in the header matches the key published in DNS (DKIM). And whether the From domain matches a domain that passed one of those checks (DMARC). DMARC also says what to do with a message that fails and where to send the report.
Gmail requires SPF or DKIM from every sender, and DMARC as well from anyone sending more than 5,000 messages a day to Gmail accounts, with a policy that may be none. DMARC is defined by RFC 9989, which replaced RFC 7489: the pct tag is now historic and t=y is used for testing.
Level
intermediate
Code
Bash
Steps
9 steps
SPFWho sendsOne TXT record, at most 10 DNS lookups.
DKIMSignatureA key from openssl and a record under a selector.
DMARCReportsp=none and rua show every sender.
Goalp=rejectForged mail from your domain is rejected.
What you need
Access to the domain's DNS zone
The registrar's or DNS provider's panel where you add TXT records. dig NS in step 1 shows who hosts the zone.
A list of everything that sends mail from the domain
The mail server, the newsletter, invoicing, the store, the CRM, the website form. Each of them must pass SPF or DKIM with your domain, or its mail stops arriving once p=reject is on.
A terminal with dig and openssl
Linux, or WSL on Windows. We ran the commands with dig 9.18.39, OpenSSL 3.0.13 and the GNU coreutils tools.
A separate mailbox for DMARC reports
Aggregate reports arrive as XML files from every mail provider that sends them. RFC 9989 recommends machine parsing, so do not point them at a mailbox someone reads every day.
Three records in DNS
Record
DNS name
Example value
SPF
example.com
v=spf1 mx include:_spf.google.com ~all
DKIM
s2026._domainkey.example.com
v=DKIM1; k=rsa; p=(public key in base64)
DMARC
_dmarc.example.com
v=DMARC1; p=none; rua=mailto:dmarc@example.com
Step by step
Each step with commands to copy. The list on the left shows where you are.
01
Check what the domain has in DNS today
Before you add anything, look at the current records. dig NS shows the name servers, so you know where you edit the zone. SPF is a TXT record on the domain itself that starts with v=spf1, and DMARC is a TXT record under the name _dmarc.
Below are the real google.com records: SPF with one include ending in ~all, and DMARC with a reject policy and a report address.
Mail sources and what each one needs
The company mail servermx, ip4:, ip6:
The server's addresses in SPF and DKIM signing switched on on that server.
Hosted emailinclude:
Google Workspace or Microsoft 365: the include the provider gives you and DKIM switched on in its panel.
Newsletters and campaignsinclude: or a subdomain
The service gives you an include or DKIM records to copy. The return address may sit on a subdomain with its own SPF.
Store, invoicing, CRM, website formip4: or include:
Sends through its own server: its address goes into SPF. Sends through a mail service: its include and DKIM are enough.
The record starts with v=spf1, then lists who may send. mx means the servers in the domain's MX record, the a mechanism the address in its A record, ip4 and ip6 specific addresses or ranges, and include pulls in a provider's SPF record. It ends with all and a qualifier that says what happens to everyone else.
-all means fail, ~all softfail. RFC 9989 warns that with -all some servers reject the message at the SPF stage, before they check DMARC. That also drops mail that would pass DMARC thanks to its DKIM signature, forwarded mail for example, and it never shows up in the reports. With DKIM and DMARC working, ~all is the safe choice. A domain that sends no mail at all can publish just v=spf1 -all.
A long record may be stored as several quoted strings, like github.com below, where the split falls in the middle of an IP address. RFC 7208 says to join them without spaces, so this is not an error.
example.com.zone
; one SPF record per domain: every mail source in one placeexample.com. 3600 IN TXT "v=spf1 mx include:_spf.google.com ~all"; wrong: two v=spf1 records on one name give permerror; example.com. 3600 IN TXT "v=spf1 mx ~all"; example.com. 3600 IN TXT "v=spf1 include:_spf.google.com ~all"
RFC 7208 allows at most 10 mechanisms that need a DNS query: include, a, mx, ptr, exists and the redirect modifier. The ones inside records pulled in by include count too. Above the limit the result is permerror, while ip4, ip6 and all cost nothing.
The script below walks the record together with nested includes and numbers every query. The github.com record uses the whole limit, ten out of ten, so one more include would already give permerror. cloudflare.com has seven.
When you run out of room, remove the includes of services you no longer use, or move a sender to a subdomain with its own SPF record, such as newsletter.example.com. With relaxed DMARC alignment the subdomain still matches the From domain.
spf-lookups.sh
#!/usr/bin/env bash# Counts the DNS lookups in an SPF record, nested includes included (the limit is 10).lookups=0walk() { local record term # a record made of several strings is joined without spaces (RFC 7208, 3.3) record=$(dig +short TXT "$1" | sed 's/" "//g; s/"//g' | grep '^v=spf1' | head -n 1) for term in $record; do case "${term#[+?~-]}" in include:*|redirect=*|a|a[:/]*|mx|mx[:/]*|ptr|ptr:*|exists:*) lookups=$((lookups + 1)) printf '%3d %*s%s\n' "$lookups" "$2" '' "$term" case "${term#[+?~-]}" in include:*|redirect=*) walk "${term#*[:=]}" $(($2 + 2)) ;; esac ;; esac done}walk "$1" 0echo "$lookups/10"
DKIM signs every message with the private key, and the receiver checks the signature with the public key from DNS. RFC 8301 requires RSA keys of at least 1024 bits and recommends at least 2048, and Google recommends 2048 bits too. umask 077 makes the key file readable only by its owner from the start.
The selector is any name you publish the key under. A name with the year, such as s2026, makes rotation easy: a new key gets a new selector, and you remove the old record only once nothing signs with it any more.
openssl pkey -in s2026.private.pem -noout -text | head -n 1
Output
Private-Key: (2048 bit, 2 primes)
05
Turn the public key into a TXT record
A DKIM record is v=DKIM1; k=rsa; p= followed by the public key in base64, without the BEGIN and END lines. openssl pkey -pubout -outform DER writes the public key in DER format, and base64 -w 0 turns it into a single line.
A 2048-bit key with the prefix is 410 characters, and a single string in a TXT record can hold at most 255. So you split it into several quoted strings, and RFC 6376 tells the receiver to join them without spaces. Some DNS panels take the whole value and split it themselves; in a zone file you do it by hand, as here.
You add the record under the name selector._domainkey.domain. In a panel that appends the domain itself you type only s2026._domainkey: the full name would end up as s2026._domainkey.example.com.example.com, which nobody will find.
You load the private key into whatever sends the mail: a server with OpenDKIM or rspamd, your mail provider's panel or the newsletter service, with the selector s2026 and the domain example.com. Service providers often generate the key themselves and give you a record to copy. That is the case at microsoft.com: the selector1 selector is a CNAME to an onmicrosoft.com domain, as shown below. The provider then holds and rotates the key and does steps 4 and 5 for you.
A wrong selector returns nothing. You can read the selector your server uses from the s= field in the DKIM-Signature header of any message it sent.
example.com.zone
; the DKIM public key under the s2026 selectors2026._domainkey.example.com. 3600 IN TXT ( "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtcnTo5pibROMrZlF/Aw+g6me8g+UaqHr53syRgnAf+7/BDNUvT91VMoGiY926ZhZxz1X94/ak0cvBMwYvH73bPo4uFzBlO8hXMTfFMVH1gqBHM6Peof0HY2HJjdqobUA1rR5kDrD14YYq77GQJdF9QVuabTnlXkHv37HSKTm63vLE673ZFKchOKdYnrsc1PIt" "mzrw5CrSs9kX0M3+t5tCuEWpSX5szwDQSagq5ei3WKc3J8muodnGNSigU95w3DwPwYcer6AmX54hAEShQvKl88Nbt2dnlzESw9cc5OhushLGz70zZCstnGkUSAzRLkd2aQyDgUaOngprKPCUi0CIwIDAQAB" )
The most common DKIM error is a record that does not match the key on the server: an old key after rotation, a cut-off fragment or a space pasted into the middle. The script fetches the record from DNS, joins the strings, decodes the key, signs a test text with the private key and verifies the signature with the key from DNS. Verified OK means the pair matches, Verification failure means DNS holds a key from another pair.
You can check the length of a published key the same way for any domain: github.com publishes a 2048-bit key under the google selector. An empty p= means, under RFC 6376, a revoked key. That is what the 20230601 selector at gmail.com looks like.
dkim-check.sh
#!/usr/bin/env bash# Checks whether the DKIM key published in DNS matches the mail server's private key.# Usage: ./dkim-check.sh selector domain key.private.pem [extra dig options]set -euo pipefailname="$1._domainkey.$2"work=$(mktemp -d)trap 'rm -rf "$work"' EXIT# a record made of several strings is joined without spaces, as with SPFkey=$(dig "${@:4}" +short TXT "$name" | sed 's/" "//g; s/"//g' | grep -o 'p=[A-Za-z0-9+/=]*' | cut -c3- || true)if [ -z "$key" ]; then echo "$name: no key in DNS (wrong selector or empty p=)" >&2 exit 1fiprintf '%s' "$key" | base64 -d > "$work/public.der"openssl pkey -pubin -inform DER -in "$work/public.der" -noout -text | head -n 1# sign with the private key, verify with the key from DNSprintf 'dkim-check %s\n' "$name" > "$work/message"openssl dgst -sha256 -sign "$3" -out "$work/signature" "$work/message"openssl dgst -sha256 -verify "$work/public.der" -keyform DER -signature "$work/signature" "$work/message"
The DMARC record is a TXT record under the name _dmarc.domain. v=DMARC1 must come first, p says what to do with a message that fails, and rua is the address for aggregate reports. RFC 9989 describes starting at p=none with rua: nothing is blocked yet, and the reports show every source of mail with your domain together with its SPF and DKIM results.
DMARC passes when SPF or DKIM passes for a domain aligned with the From field. Alignment is relaxed by default (adkim=r and aspf=r), so mail.example.com matches example.com. A service that signs with the provider's own domain passes DKIM but fails DMARC until you set your own domain in it.
Reports sent to an address in another domain need that domain's consent: a TXT record yourdomain._report._dmarc.report-domain with the value v=DMARC1. That is how cloudflare.com collects its reports in a separate domain, as the output shows.
example.com.zone
; stage 1: monitoring only, aggregate reports to a separate address_dmarc.example.com. 3600 IN TXT "v=DMARC1; p=none; rua=mailto:dmarc@example.com"
When the reports show every source of your mail with aligned SPF or DKIM, change p to quarantine. Receivers then treat messages without aligned authentication as suspicious, which can mean the spam folder. RFC 9989 sets no fixed time for this stage and notes that it can take months of reports before a domain is sure.
RFC 9989 added the t=y tag: the domain then asks for a policy one level milder, so p=quarantine behaves like none and p=reject like quarantine. Receivers that implemented only RFC 7489 do not know the t tag and ignore it, so treat it as a test signal, not a guarantee. The pct tag is now historic: github.com still publishes pct=100, which changes nothing, because 100 was the default.
The last stage is p=reject: a message that fails DMARC is to be rejected. sp sets the policy for existing subdomains and np for subdomains that do not exist. Without them p applies.
example.com.zone
; stage 2: mail without aligned SPF or DKIM is treated as suspicious_dmarc.example.com. 3600 IN TXT "v=DMARC1; p=quarantine; rua=mailto:dmarc@example.com"; stage 3, once the reports are clean: reject, also for subdomains and names that do not exist; _dmarc.example.com. 3600 IN TXT "v=DMARC1; p=reject; sp=reject; np=reject; rua=mailto:dmarc@example.com"
We served the example.com zone with the records from this guide locally in CoreDNS 1.12.4 and published the three DMARC stages one after another. dkim-check.sh fetched the key from that zone and confirmed that it matches the private key. The dkimpy library signed a message with the s2026 selector and verified the signature with the key from DNS, and after the subject was changed the verification failed.
The signing and verification script is the sign_verify.py listing below. To confirm it yourself, send a test mail from your own domain to a Gmail account and check the SPF, DKIM and DMARC results under Show original. Google Postmaster Tools also shows the authentication of mail sent to Gmail accounts.
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=example.com; i=@example.com; q=dns/txt; s=s2026; t=1794083828; h=from : to : subject : date : message-id; bh=VNyDarC8YkEJy+BngMFk6o6Pz+FZqizy22SDHwG92S4=;verify: Trueverify after editing Subject: False
sign_verify.py
import sysimport dkimimport dns.messageimport dns.queryimport dns.rdatatype# Usage: python sign_verify.py key.private.pem 127.0.0.1 15353private, server, port = open(sys.argv[1], "rb").read(), sys.argv[2], int(sys.argv[3])def txt(name, timeout=5): # dkimpy asks for selector._domainkey.domain, and we take the answer from the chosen DNS server query = dns.message.make_query(name.decode(), dns.rdatatype.TXT) for answer in dns.query.udp(query, server, port=port, timeout=timeout).answer: for record in answer: return b"".join(record.strings) return Nonemessage = ( b"From: Office <office@example.com>\r\n" b"To: customer@example.org\r\n" b"Subject: Invoice 11/2026\r\n" b"Date: Sat, 07 Nov 2026 21:30:00 +0100\r\n" b"Message-ID: <invoice-11-2026@example.com>\r\n" b"\r\n" b"Invoice attached.\r\n")signature = dkim.sign(message, b"s2026", b"example.com", private, include_headers=[b"from", b"to", b"subject", b"date", b"message-id"])signed = signature + messageprint(signature.decode().rstrip())print("verify:", dkim.verify(signed, dnsfunc=txt))# one changed character in a signed header invalidates the signatureprint("verify after editing Subject:", dkim.verify(signed.replace(b"11/2026", b"12/2026"), dnsfunc=txt))
1-2
The third DMARC stage
p=reject together with sp and np, published after the none and quarantine stages.
3-5
The key pair matches
The key in DNS has 2048 bits, and a signature made with the private key verifies.
6-10
The DKIM-Signature header
d=example.com and s=s2026 point to the s2026._domainkey.example.com record. We left out the five lines of the b= signature itself.
11-12
The signature protects the content
Changing a single character in the signed subject is enough to fail verification.
Business email with the records already set
How it looks in our project
Hand it over when several services send from the domain, when the DMARC reports show sources you do not recognise, or when you cannot afford invoices to stop arriving after p=reject.
In VulMail business email the SPF, DKIM and DMARC records are set when you connect the domain. With a website transfer we also move the email and the DNS records, and we plan the switch so there is no downtime.
No _report._dmarc authorisation record in the report recipient's domain.
Add the TXT record yourdomain._report._dmarc.report-domain with v=DMARC1.
Frequently asked questions
The questions that come up with this setup.
01
What are SPF, DKIM and DMARC?
They are three DNS records that prove a message really comes from your domain: SPF lists the servers allowed to send, DKIM signs each message and DMARC says what to do with mail that fails these checks.
02
Is SPF alone enough?
No. SPF alone breaks when mail is forwarded, because the sending server changes, as RFC 7208 describes in appendix D. So set up DKIM next to it, and Gmail requires all three from anyone sending more than 5,000 messages a day. The DKIM signature survives as long as the content does not change.
03
How often should I rotate the DKIM key?
RFC 6376 sets no period. With a selector that carries the year, rotation is simple: publish the new key under a new selector, switch signing over, and only later remove the old record or leave it with an empty p=, which marks the key as revoked.
04
Will p=reject block mail my company sends?
Only messages that pass neither SPF nor DKIM with a domain aligned with From. That is why you start with p=none and reports: they show every source before anything is rejected.
05
What should I do with pct in an old record?
RFC 9989 made it historic, and receivers following the new RFC ignore it. pct=100 changes nothing, because it was the default. t=y now does the testing job that pct=0 used to do.
06
How many DMARC records can a domain have?
One, under the name _dmarc. A subdomain can have its own _dmarc.subdomain record; without it the parent's sp applies, or p when there is no sp.
07
Why do emails from my domain land in spam?
Most often because the domain lacks correct SPF, DKIM and DMARC records, or has two SPF records instead of one. Gmail requires SPF or DKIM from every sender, so start by checking the records in step 1 and with a test mail using Show original.
Sources
The documentation and specifications we compared the commands with.
Security headers in nginxHSTS in stages, CSP with a nonce in Report-Only, nosniff, Referrer-Policy, Permissions-Policy and the add_header trap.
Tools
CIDR subnet calculatorCIDR notation writes an IPv4 network as an address and mask, like 192.168.1.0/24. Get the range, broadcast, wildcard mask, host count and subnets. Free.