SPF, DKIM, and DMARC Setup Guide: Complete Email Authentication

Step-by-step instructions for setting up SPF, DKIM, and DMARC email authentication. Protect your domain from spoofing, improve deliverability, and meet the requirements of Gmail, Yahoo, and other major providers.

Why Email Authentication Matters

Email authentication is the set of protocols that verify whether an email message genuinely comes from the domain it claims to come from. Without authentication, anyone can send an email that appears to come from your domain. Phishers use this to impersonate banks, retailers, and SaaS companies. Spammers use it to hijack the reputation of legitimate domains. Email authentication stops both of these by giving receiving servers a way to verify the sender's identity.

There are three authentication protocols that work together: SPF verifies which servers are allowed to send email for your domain, DKIM verifies that the message was not altered in transit and was signed by an authorized sender, and DMARC ties SPF and DKIM together with a policy that tells receiving servers what to do when authentication fails. All three are required for reliable email delivery in 2024 and beyond.

In February 2024, Gmail and Yahoo announced new sender requirements that mandate SPF, DKIM, and DMARC for anyone sending more than 5,000 emails per day to their users. Senders who do not comply see their messages rejected or filtered to spam. Microsoft followed with similar requirements for Outlook.com domains. These requirements apply to all bulk senders regardless of industry. Email authentication is no longer optional; it is a mandatory infrastructure requirement.

Beyond compliance, authentication directly improves email deliverability. ISPs give higher inbox placement to authenticated email because they can verify the sender's identity. Authentication also enables Brand Indicators for Message Identification (BIMI), which displays your brand logo next to your emails in supported inboxes, increasing open rates and brand trust.

Compliance Requirement: As of 2024, Gmail, Yahoo, and Microsoft require SPF, DKIM, and DMARC for all bulk email senders. Messages that fail authentication are subject to rejection or spam filtering. Setting up all three protocols is no longer optional.

SPF: Sender Policy Framework

What Is SPF?

SPF (Sender Policy Framework) is a DNS-based authentication protocol that allows domain owners to specify which mail servers are authorized to send email on behalf of their domain. If you are not yet familiar with how the SMTP protocol handles message routing, review that first. When a receiving server gets an email claiming to be from your domain, it looks up your SPF record in DNS and checks whether the sending server's IP address is listed as an authorized sender. If the IP matches, SPF passes. If not, SPF fails.

SPF works on the envelope sender address (the MAIL FROM in the SMTP conversation), not the visible From header that recipients see. This distinction is important for understanding SPF alignment, which we cover in the DMARC section below.

How to Create an SPF Record

An SPF record is published as a DNS TXT record on your domain. It starts with v=spf1 to declare the version, followed by mechanisms that define authorized senders, and ends with a qualifier that specifies how to handle unauthorized senders.

# Basic SPF record authorizing a specific IP and a third-party service
example.com.    IN    TXT    "v=spf1 ip4:203.0.113.10 include:_spf.queensmtp.com -all"

Here is what each part means:

Mechanism Purpose Example
v=spf1 Declares this is an SPF version 1 record Always the first element
ip4: Authorizes a specific IPv4 address or range ip4:203.0.113.10 or ip4:203.0.113.0/24
ip6: Authorizes a specific IPv6 address or range ip6:2001:db8::1
a Authorizes the IP(s) in the domain's A record a:mail.example.com
mx Authorizes the IP(s) of the domain's MX servers mx
include: Includes another domain's SPF record include:_spf.queensmtp.com
-all Hard fail: reject unauthorized senders Always the last element
~all Soft fail: accept but mark unauthorized senders Use during initial testing only

SPF Record Examples

# Example 1: Single mail server with dedicated IP
example.com.    IN    TXT    "v=spf1 ip4:203.0.113.10 -all"

# Example 2: Mail server + QUEENSMTP.COM + Google Workspace
example.com.    IN    TXT    "v=spf1 ip4:203.0.113.10 include:_spf.queensmtp.com include:_spf.google.com -all"

# Example 3: Multiple IPs with an IP range
example.com.    IN    TXT    "v=spf1 ip4:203.0.113.0/24 ip4:198.51.100.50 include:_spf.queensmtp.com -all"

# Example 4: Using MX servers and a third-party service
example.com.    IN    TXT    "v=spf1 mx include:_spf.queensmtp.com -all"

SPF Best Practices

Use -all (hard fail) in production. The ~all soft fail is appropriate during initial testing, but once you have confirmed all legitimate sending sources are listed, switch to -all. Hard fail tells receiving servers to reject unauthorized messages, which provides stronger protection against spoofing.

Stay within the 10 DNS lookup limit. Each include:, a:, mx:, and redirect= mechanism triggers a DNS lookup. Nested includes (an included record that itself includes another) count toward your total. If your record exceeds 10 lookups, SPF evaluation returns a permanent error (permerror) and all your email fails SPF. Use ip4: and ip6: mechanisms where possible since they do not count as DNS lookups.

Publish only one SPF record per domain. Having multiple TXT records that start with v=spf1 on the same domain is invalid and causes SPF to fail. If you need to add a new service, edit your existing SPF record rather than creating a second one.

Audit your SPF record regularly. When you add or remove email services, update your SPF record accordingly. Leaving old, unused includes wastes DNS lookups and can create security gaps if those services are compromised.

DKIM: DomainKeys Identified Mail

What Is DKIM?

DKIM (DomainKeys Identified Mail) is an authentication protocol that allows the sending server to attach a cryptographic signature to every outgoing email. This signature covers specific message headers and the body content. The receiving server retrieves the sender's public key from a DNS record and uses it to verify the signature. If the signature is valid, it proves two things: the message was sent by a server that possesses the private key for that domain, and the signed parts of the message were not modified in transit.

DKIM is more robust than SPF in several ways. It survives email forwarding because the signature is embedded in the message itself rather than being tied to the sending IP. It provides message integrity verification, detecting any tampering between sender and recipient. And it uses standard public-key cryptography, making it extremely difficult to forge.

How DKIM Works

The DKIM process involves three components: a private key stored securely on your sending server, a public key published in DNS, and a selector that identifies which key pair to use (allowing you to rotate keys and use different keys for different services).

When your server sends an email, it generates a hash of the specified headers and body, encrypts that hash with the private key, and adds the result as a DKIM-Signature header in the email. The receiving server extracts the selector and domain from this header, looks up the corresponding DNS record to get the public key, decrypts the hash, and compares it to its own calculation of the message hash. If they match, DKIM passes.

Step-by-Step DKIM Setup

Step 1: Generate a DKIM key pair. Use your MTA's built-in tools or the opendkim-genkey utility to create a 2048-bit RSA key pair. The private key stays on your server; the public key goes into DNS. If you have not yet installed and configured your MTA, our SMTP server setup guide covers the full process.

# Generate a DKIM key pair using opendkim-genkey
# -s specifies the selector name, -d specifies the domain
# -b 2048 specifies key size (2048-bit recommended minimum)

sudo opendkim-genkey -s default -d example.com -b 2048

# This creates two files:
# default.private  -- Private key (keep this secure on your server)
# default.txt      -- DNS record to publish

Step 2: Publish the public key in DNS. The public key is published as a TXT record at selector._domainkey.yourdomain.com. The selector is the name you chose when generating the key (in our example, "default").

# DKIM DNS Record
# Add this as a TXT record at: default._domainkey.example.com

default._domainkey.example.com.    IN    TXT    (
    "v=DKIM1; h=sha256; k=rsa; p="
    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2K4PavXoNY8eGK2u"
    "phCkvrvTJlsxaj5VoSOt0bOFBh2gvin+WhLTJSMYjr1JJmOPAB7VzhGx0gG6"
    "k4MXhvDRSAEfOKXLA/N4dPaYMXDXgA+GVhwjrBBi8MjJaw4bTYcvMPSQXbhm"
    "QyRNRB0VCnqLxgg0Iqg2W6NsHg1bJAQplYVo0ir0nDqfF93ljBeAz5Jcihz2h"
    "... (full base64-encoded public key) ..."
    "AQAB" )

# Note: Long keys are split across multiple strings in DNS
# Your DNS provider may handle this differently

Step 3: Configure your MTA to sign outgoing email. Install and configure OpenDKIM (or your MTA's built-in DKIM support) to sign outgoing messages using the private key.

# OpenDKIM configuration (/etc/opendkim.conf)

Syslog              yes
UMask               007
Mode                sv          # Sign and verify
Canonicalization    relaxed/relaxed
Domain              example.com
Selector            default
KeyFile             /etc/opendkim/keys/example.com/default.private
Socket              inet:8891@localhost

# Postfix integration (/etc/postfix/main.cf)
# Add these lines to connect Postfix to OpenDKIM:

milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891

Step 4: Test and verify. Send a test email to a Gmail address and view the original message headers. Look for the dkim=pass result in the Authentication-Results header. Also verify using an external tool like mail-tester.com or dkimvalidator.com.

DKIM Best Practices

Use 2048-bit keys minimum. 1024-bit RSA keys are considered weak and some providers may reject them. 2048-bit keys provide adequate security for current standards. Some organizations are moving to 4096-bit keys, but be aware that very long keys may need to be split across multiple DNS TXT strings, and some DNS providers have issues with records exceeding 255 characters per string.

Use relaxed/relaxed canonicalization. Canonicalization determines how strictly the message must match the signed content. "Relaxed" mode tolerates minor whitespace changes that can occur during mail relay (such as trailing spaces or header line wrapping). "Simple" mode requires an exact match and is more likely to break during forwarding. Setting both header and body to "relaxed" (relaxed/relaxed) provides the best balance of security and reliability.

Rotate keys annually. Generate a new key pair with a new selector name at least once a year. Publish the new public key, update your server to sign with the new private key, and keep the old public key in DNS for a transition period (at least 7 days) so that messages signed with the old key and still in transit can be verified. After the transition period, remove the old DNS record.

Sign the right headers. At minimum, sign the From, To, Subject, Date, and MIME-Version headers. Most DKIM implementations also sign Reply-To, Message-ID, Content-Type, and Content-Transfer-Encoding. The From header is mandatory for DMARC alignment. Avoid signing headers that are commonly modified by mailing lists (like List-Unsubscribe) to prevent signature breakage.

DMARC: Domain-based Message Authentication

What Is DMARC?

DMARC (Domain-based Message Authentication, Reporting, and Conformance) is a protocol that builds on top of SPF and DKIM. It serves two purposes: it tells receiving servers what to do when an email fails authentication (the policy), and it provides a reporting mechanism that sends you data about who is sending email using your domain (the reports). DMARC closes the gaps left by SPF and DKIM individually, creating a complete authentication framework.

Without DMARC, a receiving server might pass a message that has a valid SPF record but the SPF domain does not match the From header domain. DMARC introduces the concept of alignment, requiring that the authenticated domain (from SPF or DKIM) matches the domain in the visible From header. This prevents attackers from using a legitimate SPF-authenticated server to send email with a spoofed From address.

DMARC Record Structure

A DMARC record is published as a DNS TXT record at _dmarc.yourdomain.com. Here are the most important tags:

Tag Required Purpose Values
v Yes Protocol version Must be DMARC1
p Yes Policy for the domain none, quarantine, reject
sp No Policy for subdomains none, quarantine, reject
rua No (recommended) Aggregate report destination mailto:dmarc@example.com
ruf No Forensic report destination mailto:forensic@example.com
pct No Percentage of messages to apply policy 1 to 100 (default: 100)
adkim No DKIM alignment mode r (relaxed) or s (strict)
aspf No SPF alignment mode r (relaxed) or s (strict)

Step-by-Step DMARC Setup

Step 1: Start with monitoring mode (p=none). Before enforcing any policy, you need to understand who is sending email on behalf of your domain. A p=none policy tells receiving servers to take no action on failing messages but to send you reports.

# Phase 1: Monitor only (start here)
_dmarc.example.com.    IN    TXT    "v=DMARC1; p=none; rua=mailto:dmarc-reports@example.com; pct=100"

Step 2: Analyze aggregate reports for 2 to 4 weeks. Aggregate reports (rua) are XML files sent daily by ISPs showing the authentication results for every email sent from your domain. These reports tell you which IP addresses are sending email as your domain, whether SPF and DKIM passed, and whether alignment succeeded. Use a DMARC report analyzer (like DMARCian, Postmark DMARC, or DMARC Analyzer) to parse and visualize these reports. Identify all legitimate sending sources (your SMTP server, CRM, marketing platform, transactional service) and make sure each one passes SPF or DKIM with proper alignment.

Step 3: Authenticate all legitimate sources. For every legitimate sending source identified in the reports, ensure it is either listed in your SPF record (with proper alignment) or signing with your DKIM key (with proper alignment). This may involve configuring SPF includes for third-party services, setting up DKIM signing for each service using your domain's keys, or using the service's CNAME-based DKIM setup to achieve alignment.

Step 4: Move to quarantine with a percentage. Once all legitimate sources are authenticated, gradually enforce the policy by moving to p=quarantine with a low percentage and increasing it over time.

# Phase 2: Quarantine 25% of failing messages
_dmarc.example.com.    IN    TXT    "v=DMARC1; p=quarantine; rua=mailto:dmarc-reports@example.com; pct=25"

# Phase 3: Quarantine 50% of failing messages
_dmarc.example.com.    IN    TXT    "v=DMARC1; p=quarantine; rua=mailto:dmarc-reports@example.com; pct=50"

# Phase 4: Quarantine all failing messages
_dmarc.example.com.    IN    TXT    "v=DMARC1; p=quarantine; rua=mailto:dmarc-reports@example.com; pct=100"

Step 5: Move to reject. After running at quarantine with pct=100 for at least two weeks with no legitimate email being quarantined, move to the p=reject policy. This tells receiving servers to outright reject any message that fails both SPF and DKIM alignment. This is the strongest protection against domain spoofing.

# Phase 5: Full enforcement - reject all unauthorized email
_dmarc.example.com.    IN    TXT    "v=DMARC1; p=reject; sp=reject; rua=mailto:dmarc-reports@example.com; adkim=s; aspf=s; pct=100"

# Breakdown:
# p=reject    -- Reject email failing authentication for the main domain
# sp=reject   -- Reject email failing authentication for all subdomains
# adkim=s     -- Strict DKIM alignment (exact domain match required)
# aspf=s      -- Strict SPF alignment (exact domain match required)
# pct=100     -- Apply to 100% of messages

DMARC Policy Impact

Policy Action on Failure Use Case
p=none No action, monitoring only Initial deployment. Gather data before enforcing.
p=quarantine Send failing messages to spam/junk Intermediate step. Catches spoofing while allowing review of false positives.
p=reject Reject failing messages entirely Full enforcement. Maximum protection against spoofing and phishing.

Understanding SPF and DKIM Alignment

Alignment is the concept that makes DMARC more powerful than SPF or DKIM alone. DMARC requires that at least one of SPF or DKIM not only passes but also aligns with the domain in the visible From header. This prevents a common attack where a spammer passes SPF (because they control the envelope sender domain) while spoofing a different domain in the From header.

SPF Alignment

SPF alignment means the domain in the envelope sender (MAIL FROM) matches the domain in the From header. In strict mode (aspf=s), the domains must be identical. In relaxed mode (aspf=r), the organizational domain (the registered domain) must match, allowing subdomains. For example, if your From header is user@example.com and the envelope sender is bounce@mail.example.com, strict alignment fails (different hostnames) but relaxed alignment passes (same organizational domain: example.com).

Many third-party services send email using their own envelope sender domain (for bounce processing), which breaks SPF alignment. This is why DKIM alignment is often more reliable for DMARC compliance when using third-party senders.

DKIM Alignment

DKIM alignment means the domain in the DKIM signature's d= tag matches the domain in the From header. In strict mode (adkim=s), they must be identical. In relaxed mode (adkim=r), the organizational domains must match. Most SMTP services support signing with your domain (either by you providing your DKIM private key or by using CNAME records to delegate the DKIM namespace), which ensures DKIM alignment.

DMARC passes if either SPF or DKIM (or both) both passes and aligns. This means you do not need both to align. If your third-party service breaks SPF alignment but you have properly configured DKIM signing with your domain, DMARC will pass on DKIM alignment alone.

QUEENSMTP.COM Alignment: QUEENSMTP.COM supports custom DKIM signing for your domain and can be configured as an authorized SPF sender. Both SPF and DKIM alignment are verified during our guided setup process, ensuring DMARC compliance from the first email you send.

Verification and Testing Tools

After configuring SPF, DKIM, and DMARC, you must verify that everything works correctly. Do not assume records are correct simply because you published them. DNS propagation issues, syntax errors, and misconfigured selectors are common pitfalls.

DNS Record Verification

# Verify SPF record
dig TXT example.com +short
# Expected: "v=spf1 ip4:203.0.113.10 include:_spf.queensmtp.com -all"

# Verify DKIM record
dig TXT default._domainkey.example.com +short
# Expected: "v=DKIM1; k=rsa; p=MIIBIjANBg..."

# Verify DMARC record
dig TXT _dmarc.example.com +short
# Expected: "v=DMARC1; p=reject; rua=mailto:dmarc-reports@example.com..."

# Check MX records (useful for overall email config verification)
dig MX example.com +short
# Expected: 10 mail.example.com.

Send a Test Email and Check Headers

Send a test email to a Gmail account, open the message, click the three dots menu, and select "Show original." Look for the Authentication-Results header, which shows the results for SPF, DKIM, and DMARC. All three should show "pass." If any shows "fail," "softfail," or "neutral," investigate the corresponding DNS record and server configuration.

# What to look for in Gmail's "Show original" view:

Authentication-Results: mx.google.com;
    dkim=pass header.i=@example.com header.s=default header.b=abc123;
    spf=pass (google.com: domain of sender@example.com designates 203.0.113.10 as permitted sender) smtp.mailfrom=sender@example.com;
    dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=example.com

# All three should show "pass"
# dkim=pass means DKIM signature verified successfully
# spf=pass means the sending IP is authorized by SPF
# dmarc=pass means at least one of SPF/DKIM passed with alignment

Online Verification Tools

MXToolbox SPF Checker validates your SPF record syntax, counts DNS lookups (to check the 10-lookup limit), and identifies potential issues. Run this check every time you modify your SPF record.

mail-tester.com provides a comprehensive email test. Send an email to the address they provide, and they check SPF, DKIM, DMARC, content quality, blacklist status, and more, returning a score out of 10 with specific recommendations for any issues found.

DKIM Validator (dkimvalidator.com) specifically tests DKIM signing. Send an email to their test address and they verify the DKIM signature, check the DNS record, and report any issues with key size, canonicalization, or signed headers.

Google Admin Toolbox Check MX tests your domain's MX records, SPF, DKIM, and DMARC configuration from Google's perspective. Since Gmail is the largest email provider, passing their checks is essential.

Common Issues and Troubleshooting

SPF: "Too many DNS lookups" (permerror)

If your SPF record requires more than 10 DNS lookups, SPF returns a permanent error and all your email fails SPF. Count every include:, a:, mx:, and redirect= mechanism, plus any nested includes within those records. To fix this, replace include: mechanisms with direct ip4: or ip6: addresses where possible (these do not count as lookups), use an SPF flattening service that periodically resolves includes and replaces them with IP addresses, or consolidate services that share infrastructure.

SPF: Multiple SPF Records

Having two or more TXT records that start with v=spf1 on the same domain is invalid per the RFC and causes SPF to fail. This commonly happens when someone adds a new SPF record instead of editing the existing one. Check with dig TXT example.com and ensure there is only one SPF record. Merge all authorized sources into a single record.

DKIM: Signature Verification Fails

Common causes include the DNS record not being published yet (propagation can take up to 48 hours), the selector in the DKIM-Signature header not matching the selector in DNS, the public key in DNS being truncated or having formatting errors, the private key on the server not matching the public key in DNS (regenerate the key pair if unsure), and message modification by an intermediate server breaking the signature.

DKIM: Key Too Short

If you are still using 512-bit or 1024-bit DKIM keys, some receivers may reject or downgrade your authentication. Generate new 2048-bit keys and publish them with a new selector. Keep the old key in DNS during the transition period, then remove it.

DMARC: Alignment Failure Despite SPF and DKIM Passing

This is the most confusing DMARC issue. SPF and DKIM both pass individually, but DMARC fails because neither aligns with the From header domain. This typically happens when a third-party service passes SPF for its own domain (not yours) and signs DKIM with its own domain (not yours). The fix is to configure the third-party service to use your domain for DKIM signing (most services support this via CNAME records) or to add the service's sending IPs to your SPF record with proper envelope sender configuration.

DMARC: Reports Not Being Received

If the email address in your rua tag is on a different domain than your DMARC record, the receiving domain must publish a special DNS record authorizing your domain to receive its reports. For example, if your DMARC record is on example.com but reports go to dmarc@reports.net, reports.net must publish: example.com._report._dmarc.reports.net. IN TXT "v=DMARC1". If reports go to an address on the same domain as the DMARC record, no additional authorization is needed.

Advanced Configuration

Subdomain Policies

The sp tag in your DMARC record sets the policy for subdomains. If you do not specify sp, subdomains inherit the p policy. For maximum security, set sp=reject to prevent spoofing of subdomains you do not use for email. If you use specific subdomains for sending (like marketing.example.com or transactional.example.com), you can publish separate DMARC records on those subdomains with their own policies.

DKIM Key Rotation Procedure

To rotate DKIM keys without disruption: generate a new key pair with a new selector name (for example, change from "default" to "jan2025"), publish the new public key in DNS and wait for propagation (24 to 48 hours), update your signing configuration to use the new selector and private key, verify DKIM is passing with the new key by sending test emails, and after 7 days remove the old selector's DNS record. The overlap period ensures that emails signed with the old key and still in transit or in retry queues can be verified.

BIMI (Brand Indicators for Message Identification)

BIMI allows your brand logo to appear next to your emails in recipient inboxes that support it (Gmail, Yahoo, Apple Mail). BIMI requires a DMARC policy of p=quarantine or p=reject. You publish a BIMI DNS record pointing to your logo (SVG format) and, for Gmail, obtain a Verified Mark Certificate (VMC) from a certificate authority. BIMI increases brand visibility and open rates, and it is only available to senders with strong authentication.

# BIMI DNS Record (requires DMARC p=quarantine or p=reject)
default._bimi.example.com.    IN    TXT    "v=BIMI1; l=https://example.com/brand/logo.svg; a=https://example.com/brand/vmc.pem"
Need Help? Email authentication can be complex, especially when managing multiple sending services and subdomains. QUEENSMTP.COM provides a guided setup wizard that generates your DNS records, verifies your configuration, and ensures SPF, DKIM, and DMARC alignment before you send your first email.

Email Authentication FAQ

Yes, all three are recommended. SPF validates the sending server, DKIM verifies message integrity, and DMARC ties them together with a policy. Together they provide complete email authentication and are required by Gmail and Yahoo as of 2024.

Start with p=none to monitor authentication results without affecting delivery. After reviewing DMARC reports for 2-4 weeks and confirming all legitimate sources pass, move to p=quarantine, then p=reject.

Ensure all services that send email on your behalf are included in your SPF record. Common missing entries include marketing tools, CRM systems, helpdesk software, and transactional email services.

Yes, SPF has a 10 DNS lookup limit. Exceeding this causes SPF to fail. Consolidate IP ranges, use ip4/ip6 mechanisms instead of includes where possible, and remove unused entries.

Without proper authentication, your emails are much more likely to land in spam folders or be rejected entirely. Gmail and Yahoo now require SPF, DKIM, and DMARC for bulk senders. QUEENSMTP.COM provides automated setup to ensure your authentication is always configured correctly.

No, each domain should have only one SPF record. If you use multiple email services, combine all authorized servers into a single SPF record using include mechanisms. QUEENSMTP.COM provides the exact include value to add to your existing SPF record.

Start with p=none (monitoring only) to collect reports without affecting delivery. Once you verify that all legitimate email passes authentication, move to p=quarantine, then eventually p=reject for maximum protection. QUEENSMTP.COM dashboard helps you monitor DMARC results throughout this process.

Send a test email and check the email headers for SPF=pass, DKIM=pass, and DMARC=pass results. QUEENSMTP.COM dashboard shows authentication status for all sent emails, and our setup wizard verifies records before you start sending.

Get Authentication Right the First Time

QUEENSMTP.COM includes automated SPF, DKIM, and DMARC setup with every account. Our guided wizard generates your DNS records, verifies configuration, and ensures full authentication before you start sending.