Build a Python Email Header Analyzer: Spot Spoofed Emails Before You Open Them


Every phishing email looks legitimate in the inbox — the sender name matches your bank, your boss, your delivery company. But the “From” line is just a label anyone can type. The real story lives in the email headers: the authentication results, the server chain, and the return path. Today we’ll build a Python tool that reads those headers and tells you, in seconds, whether an email is what it claims to be.

What the Headers Tell You

Three authentication checks matter most:

  • SPF (Sender Policy Framework) — does the sending server appear on the domain’s approved list? A pass means the server is authorized; a fail means it isn’t.
  • DKIM (DomainKeys Identified Mail) — is the message cryptographically signed by the domain? A valid signature proves the content wasn’t altered in transit.
  • DMARC — the domain owner’s policy: what should happen when SPF or DKIM fail — nothing, quarantine, or reject.

Then there’s the Received chain — every mail server the message passed through, in reverse order. A “bank” email that first appears on a server in a country the bank doesn’t operate in is a red flag.

The Code

import re
from email import policy
from email.parser import BytesParser

def analyze_headers(raw_email: bytes):
    msg = BytesParser(policy=policy.default).parsebytes(raw_email)
    report = {}

    # 1. Authentication results (SPF / DKIM / DMARC)
    auth = msg.get("Authentication-Results", "")
    for check in ("spf", "dkim", "dmarc"):
        m = re.search(rf"{check}=(\w+)", auth, re.IGNORECASE)
        report[check] = m.group(1).lower() if m else "missing"

    # 2. From vs Return-Path mismatch
    from_addr = str(msg.get("From", ""))
    return_path = str(msg.get("Return-Path", ""))
    from_domain = re.search(r"@([\w.-]+)", from_addr)
    rp_domain = re.search(r"@([\w.-]+)", return_path)
    report["from_domain"] = from_domain.group(1) if from_domain else "?"
    report["return_path_domain"] = rp_domain.group(1) if rp_domain else "?"
    report["domain_match"] = (
        report["from_domain"] == report["return_path_domain"]
    )

    # 3. Received chain — where did this mail really come from?
    received = msg.get_all("Received", [])
    hops = []
    for h in received:
        ip = re.search(r"\[(\d+\.\d+\.\d+\.\d+)\]", h)
        host = re.search(r"from\s+([\w.-]+)", h)
        hops.append(f"{host.group(1) if host else '?'} "
                    f"({ip.group(1) if ip else 'no IP'})")
    report["hops"] = hops

    # 4. Verdict
    fails = [c for c in ("spf", "dkim", "dmarc")
             if report[c] in ("fail", "missing")]
    if fails or not report["domain_match"]:
        report["verdict"] = "SUSPICIOUS — check before trusting"
    else:
        report["verdict"] = "LOOKS OK — auth passed, domains match"
    return report

if __name__ == "__main__":
    with open("suspicious.eml", "rb") as f:
        result = analyze_headers(f.read())
    for key, value in result.items():
        print(f"{key}: {value}")

How It Works

  1. Parsing — Python’s built-in email library parses the raw .eml file. Save any suspicious email as .eml from your mail client first.
  2. Auth checks — a regex pulls spf=, dkim= and dmarc= results out of the Authentication-Results header.
  3. Domain match — the From domain and the Return-Path domain should agree. A mismatch is the classic spoofing signature: the visible sender says “your bank,” the return path says something else entirely.
  4. Received chain — each Received header is one hop. Read them bottom-to-top for the real journey of the message.

Try It

Save a suspicious email as suspicious.eml, run python3 header_check.py, and read the verdict. Then test it on a genuine email from your bank and compare — the difference is usually obvious.

Level Up

  • Add a DNS lookup for the sender domain’s SPF record using the dnspython library, so you can verify SPF yourself instead of trusting the header.
  • Flag display-name tricks — when the visible name says “Your Bank” but the address is a random Gmail account.
  • Turn it into a small web tool your whole team can paste headers into.

Phishing works because people trust what they see. Headers are what you can’t fake without leaving a trace — and now you can read them.

Only test systems you own or have written permission to test.

Comments

Popular Posts