Almost every breach that begins with a message begins with a message that was technically allowed to arrive. Email was designed for a friendlier internet, so the protocol itself verifies nothing: the From address a user sees can be entirely unrelated to the machine that connected to your mail server. Defending the channel means closing that gap with authentication records, layering content analysis that scores rather than guesses, and building a review process where a suspicious message reaches a human within minutes rather than a user's curiosity reaching an attacker's server. Each layer covers what the previous one cannot.
SPF, DKIM and DMARC: three records, one decision
Authentication works by publishing claims in DNS and having receivers check them. SPF lists which machines are permitted to send for your domain. DKIM attaches a cryptographic signature to outgoing mail that the receiving server can verify against your public key. DMARC ties the two together: it tells a receiver what alignment it should require between the visible From domain and the authenticated identity, and what to do when the check fails. None of the three is sufficient alone â SPF can be forged in the envelope, DKIM signs a domain that may not match what the user reads, and only DMARC connects them.
| Record | Publishes | Checks | Failure mode if skipped |
|---|---|---|---|
| SPF | Allowed sender IP ranges | Envelope sender against your IPs | Anyone can send as your domain |
| DKIM | Public key and selector | Signature over message headers | Forwarded or altered mail cannot prove origin |
| DMARC | Alignment policy plus reports | SPF and DKIM results against the visible From | Spoofed mail reaches inboxes with your name on it |
The records themselves are short. The example below authorizes your mail provider and your own relay, publishes a DKIM public key, and instructs receivers to reject mail that fails alignment while sending aggregate reports to your security mailbox.
example.com. IN TXT "v=spf1 mx ip4:203.0.113.10 include:_spf.mailhost.example -all"
selector2026._domainkey IN TXT "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A..."
_dmarc.example.com. IN TXT "v=DMARC1; p=reject; sp=reject; adkim=s; aspf=s; pct=100; rua=mailto:dmarc-reports@example.com; fo=1"
The -all at the end of SPF matters more than it looks: a soft ~all tells receivers to accept anything unlisted, which invites abuse from hosts you never authorized. Similarly, adkim=s and aspf=s enforce strict alignment, so a message signed by a third-party platform on your behalf will fail unless you have deliberately included it.
Rolling out DMARC without breaking legitimate mail
Jumping straight to p=reject is the most common way an organization sets its own marketing campaigns to spam. The safe path is staged: publish the record in monitoring mode, collect reports, fix every legitimate sender you did not know about â ticketing systems, invoicing portals, CRM platforms, office multifunction printers â and only then tighten enforcement. Aggregate reports arrive as XML attachments and tell you which sending IPs claimed your domain and whether SPF or DKIM passed.
# Stage 1 â observe only, no mail is affected
dig +short TXT _dmarc.example.com
# Summarize a week of aggregate reports: who is sending as us?
for f in ~/dmarc/aggregate-*.xml; do
xmllint --xpath '//record/row/source/text()' "$f" 2>/dev/null
echo
done | sort | uniq -c | sort -rn | head -20
# Stage 2 â after every legitimate sender is aligned
# Update the record to quarantine, watch for false positives for 14 days
# Stage 3 â move to reject once reports show only authorized sources
Expect the first report pass to surface surprises: a forgotten newsletter tool, a development staging environment, or a partner company sending on your behalf. Each one needs either an SPF include and DKIM key or an official decision to stop sending. Once the report shows only known sources for two consecutive weeks, tightening to quarantine then reject is low risk.
Content filtering that scores instead of guessing
Keyword blocking is the oldest filter design and the weakest: attackers adapt instantly, and legitimate messages use the same words. A scoring model is more durable because it combines many weak signals, so no single phrase decides the outcome. The filter below accumulates points from sender reputation, link mismatch, urgency language, and attachment type, then applies a threshold you can tune against real traffic.
import re
from urllib.parse import urlparse
URGENCY_PATTERNS = [
r"act now", r"immediately", r"your account will be (closed|suspended)",
r"verify your (identity|password)", r"unusual sign-in activity",
]
SUSPICIOUS_EXTENSIONS = (".exe", ".scr", ".js", ".vbs", ".iso", ".lnk")
def score_message(sender, subject, body, links, attachments):
score = 0
reasons = []
sender_domain = sender.split("@")[-1]
for link in links:
host = urlparse(link).netloc
if host and sender_domain not in host:
score += 3
reasons.append(f"link host {host} does not match sender")
break
text = f"{subject} {body}".lower()
hits = [p for p in URGENCY_PATTERNS if re.search(p, text)]
if hits:
score += 2 * len(hits)
reasons.append("urgency language: " + ", ".join(hits))
if any(a.lower().endswith(SUSPICIOUS_EXTENSIONS) for a in attachments):
score += 5
reasons.append("executable attachment")
if re.search(r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b", text):
score += 4
reasons.append("payment card pattern in body")
verdict = "quarantine" if score >= 6 else ("review" if score >= 3 else "deliver")
return verdict, score, reasons
print(score_message(
"billing@examp1e-secure.com",
"Urgent: your account will be suspended",
"Verify your identity now to avoid closure.",
["https://accounts.examp1e-secure.com/login"], ["invoice.html"],
))
Tune thresholds by replaying a sample of real mail through the scorer and measuring both false positives and what slipped through. Quarantine is almost always the right action for mid-range scores; delivering or blocking outright on a score of two will generate helpdesk tickets that erode trust in the whole system.
Reading a phishing attempt like an analyst
Users do not need to understand DKIM to be useful, but they do need a short list of concrete signals. Train on indicators that are objectively checkable rather than on vague advice to "be careful," and give people a one-click reporting path so that a message lands with the security team within minutes.
| Signal | What to check | Why it matters |
|---|---|---|
| Display name vs address | Compare the name to the actual domain | Attackers spoof names, not authentication results |
| Link target | Hover or copy the URL before clicking | Look-alike domains and URL shorteners hide destinations |
| Reply-to mismatch | Send a test reply and inspect the header | Replies routed elsewhere often indicate takeover |
| Request for secrets | Any prompt for passwords or MFA codes | Legitimate providers never ask over email |
| Unexpected attachment | Type, sender, and whether you expected it | Macro and archive payloads are a primary delivery path |
| Urgency and threat | Pressure to act within minutes | Emotional pressure exists to skip verification |
Reported messages should be converted into detections: extract the sending infrastructure, add it to your blocklist, and check whether anyone opened the link so that session can be revoked before it is used.
What your mail logs should be telling you
Authentication records only pay off if someone reads the results. Aggregate DMARC reports show who is sending as your domain, but day-to-day monitoring of the gateway surfaces the problems that arrive first: a surge in rejected messages that usually means a partner misconfigured a relay, a jump in outbound volume that often means a mailbox has been compromised to send on the owner's behalf, and TLS negotiation failures that silently downgrade delivery to plaintext. Give this review a fixed weekly rhythm with numbers attached, because a list of questions without thresholds turns into a conversation about vibes.
# Weekly mail-flow review â each line needs a number and an owner
Outbound volume vs 30-day baseline: +12% alert above +40%
Messages failing SPF or DKIM alignment: 0.4% investigate above 1%
TLS negotiation failures to partner domains: 3 each needs a ticket
Mailbox rules creating external forwards: 2 review both immediately
Top inbound rejection reasons: auth, content, reputation
Accounts with repeated auth failures (p95): 4 reset and investigate
Repeated authentication failures deserve more attention than the raw rejection count, because credential stuffing shows up there days before any account is taken over. Similarly, a newly created forward rule pointing at an external address is one of the quietest signs of a compromised mailbox, and it is visible long before the attacker sends anything. Both signals are cheap to monitor and expensive to discover late.
Encryption for content that cannot travel in the clear
Authentication proves who sent a message; it does not protect what the message says. For contracts, health information, and credentials, encrypt the content itself. TLS protects mail while it moves between servers, but the message sits in the clear at rest on the recipient's server â true confidentiality requires S/MIME or PGP, or a secure-portal link that requires the recipient to authenticate before reading. The snippet below sends a message over an encrypted transport with the correct modern authentication flow.
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["Subject"] = "Contract renewal terms"
msg["From"] = "legal@example.com"
msg["To"] = "counsel@partner.example"
msg.set_content("Attached are the revised terms. Please review section 4.")
# Opportunistic TLS: encrypt the transport between mail servers
with smtplib.SMTP("smtp.example.com", 587, timeout=30) as server:
server.ehlo()
server.starttls()
server.login("legal@example.com", app_password)
server.send_message(msg)
# Confirm the receiving server actually negotiated TLS
import socket
with socket.create_connection(("smtp.example.com", 587)) as sock:
print("SMTP extension offered:", sock.recv(1024).decode(errors="replace"))
Verify the outcome rather than assuming it: if the receiving server does not offer STARTTLS, most clients silently fall back to plaintext. For regulated content, require TLS with a documented list of partner certificates and refuse delivery when encryption cannot be established.
đĄMeasure the human layer too
Common Mistakes
Publishing SPF with a soft `~all` and never tightening it
Fix: Enumerate every legitimate sender, then publish `-all` so unauthorized sources are explicitly rejected.
Jumping from no DMARC record straight to `p=reject`
Fix: Stage through `p=none`, fix every sender surfaced in aggregate reports, then quarantine before rejecting.
Blocking on individual keywords instead of scoring combinations of signals
Fix: Use a weighted score with a tunable threshold so no single phrase can block legitimate mail.
Training users with abstract warnings about phishing
Fix: Teach three objectively checkable signals and provide a one-click report button in the mail client.
Assuming TLS encrypts email end to end
Fix: TLS protects transport only; use S/MIME, PGP, or a secure portal for content that must stay confidential at rest.
Best Practices
- Publish SPF, DKIM, and DMARC together, with strict alignment and aggregate reporting from day one.
- Route all reports to a monitored mailbox and review them weekly during the rollout, monthly afterwards.
- Score messages on multiple weak signals and quarantine the middle range instead of guessing.
- Convert every reported phish into a detection so the same infrastructure cannot target a second person.
- Require multi-factor authentication everywhere, so a harvested password alone cannot open an account.
Key Takeaways
- Email authenticates nothing by default; SPF, DKIM, and DMARC supply the missing proof and a policy for failures.
- DMARC should be deployed in stages, using aggregate reports to discover legitimate senders before enforcement.
- Scoring filters outperform keyword blocks because attackers adapt to single rules but cannot defeat every weak signal simultaneously.
- Phishing review works best when trained on checkable indicators and supported by a fast reporting path.
- Transport encryption is not message encryption; content that must remain confidential needs S/MIME, PGP, or a secure portal.