Email Header Analyzer — Python source
Paste raw email headers to trace the message path, detect spoofing, and check SPF/DKIM/DMARC authentication results. Runs entirely in your browser.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""email-header-analyzer — RFC 5322 header parser + spoofing / authentication analysis.
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `email-header-analyzer` tool, ported from
src/lib/email-header-analyzer.ts (the canonical TypeScript implementation).
Pure string parsing — no network, no DNS, deterministic. Dates go through
``email.utils.parsedate_to_datetime`` (the stdlib RFC 2822 parser) in place of
the TS ``Date.parse``; a zone-less timestamp is read as UTC.
display source — part of CosmoDev's polyglot tool pages.
"""
import re
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from typing import List, Optional
@dataclass
class Header:
"""One unfolded header line (RFC 5322)."""
name: str
value: str
@dataclass
class Hop:
"""One relay leg, chronological; ``delay`` = seconds since the previous hop."""
from_addr: str # the TS ``from`` — reserved word in Python
by: str
timestamp: Optional[datetime]
delay: Optional[float]
protocol: str
@dataclass
class AuthResult:
"""One SPF/DKIM/DMARC verdict a relay recorded in Authentication-Results."""
result: str = "none" # pass / fail / softfail / neutral / none / temperror / permerror / unknown
domain: Optional[str] = None
selector: Optional[str] = None
policy: Optional[str] = None # DMARC ``p=`` token (dmarc only)
detail: Optional[str] = None # the full authentication clause, when present
@dataclass
class AuthResults:
spf: AuthResult
dkim: AuthResult
dmarc: AuthResult
@dataclass
class Anomaly:
"""One suspicious pattern worth surfacing to a human."""
type: str
severity: str # 'critical' | 'warning' | 'info'
message: str
@dataclass
class ParsedHeaders:
headers: List[Header]
hops: List[Hop] # chronological: hops[0] is the OLDEST hop (parsed bottom-up)
auth: AuthResults
anomalies: List[Anomaly]
_SUSPICIOUS_MAILERS = ("bulk", "mass mail", "massmail", "storm", "flood", "bomber", "grabber",
"harvest", "spambot", "stealth", "anonymous", "dark", "crack")
_BRACKET_ADDRESS = re.compile(r"<([^<>\s]+)>")
_BARE_ADDRESS = re.compile(r'[^\s<>,;"\']+@[^\s<>,;"\']+')
_DATE_LOOKING_LINE = re.compile(r"\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s+[^\n]+")
def parse_header_lines(raw: str) -> List[Header]:
"""Split raw header text into unfolded name/value pairs. Stops at the first empty line."""
headers: List[Header] = []
current: Optional[Header] = None
for line in raw.replace("\r\n", "\n").split("\n"):
if not line.strip():
break # end of headers / blank separator
if current is not None and (line.startswith(" ") or line.startswith("\t")):
current.value += " " + line.strip() # RFC 5322 folding continuation
continue
colon = line.find(":")
if colon <= 0:
continue # not a header line — skip garbage
current = Header(line[:colon].strip(), line[colon + 1:].strip())
headers.append(current)
return headers
def get_headers(headers: List[Header], name: str) -> List[str]:
"""All values for a header name, case-insensitive, in file order."""
wanted = name.lower()
return [h.value for h in headers if h.name.lower() == wanted]
def extract_address(value: str) -> Optional[str]:
"""Extract an email address: prefers <addr>, falls back to the first bare address."""
bracket = _BRACKET_ADDRESS.search(value)
if bracket:
return bracket.group(1)
bare = _BARE_ADDRESS.search(value)
return bare.group(0) if bare else None
def parse_rfc2822_date(value: str) -> Optional[datetime]:
"""Parse an RFC 2822 date, ignoring trailing "(ZONE)" comments. None when unparseable."""
cleaned = re.sub(r"\([^)]*\)", " ", value).strip()
if not cleaned:
return None
try:
parsed = parsedate_to_datetime(cleaned)
except (ValueError, TypeError): # ValueError on 3.10+, TypeError on some 3.9 paths
return None
if parsed is None: # pre-3.10 lenient behaviour
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc) # zone-less timestamp: read as UTC
return parsed
def _hop_token(value: str, keyword: str) -> str:
"""First ``keyword <space> token`` in a Received value (mirrors the lib's from/by/with regexes)."""
m = re.search(r"\b" + keyword + r"\s+([^\s;()]+)", value, re.I)
return m.group(1) if m else ""
def _trim_dot(token: Optional[str]) -> Optional[str]:
return re.sub(r"[.,]$", "", token) if token else token
def parse_received(value: str) -> Hop:
"""Parse one Received header value into a hop (delay is filled in by parse_headers)."""
timestamp = parse_rfc2822_date(value.rsplit(";", 1)[1]) if ";" in value else None
if timestamp is None:
# Some clients omit the ';' — fall back to the first date-looking token.
guess = _DATE_LOOKING_LINE.search(value)
if guess:
timestamp = parse_rfc2822_date(guess.group(0))
return Hop(from_addr=_trim_dot(_hop_token(value, "from")), by=_trim_dot(_hop_token(value, "by")),
timestamp=timestamp, delay=None, protocol=_hop_token(value, "with"))
def parse_auth_results(values: List[str]) -> AuthResults:
"""Parse Authentication-Results clauses, e.g. "mx.google.com; spf=pass smtp.mailfrom=a@b.com"."""
auth = AuthResults(AuthResult(), AuthResult(), AuthResult())
def token(clause: str, key: str) -> Optional[str]:
m = re.search(r"\b" + key + r"=([^\s;)]+)", clause, re.I)
return _trim_dot(m.group(1)) if m else None
for value in values:
for raw_clause in value.split(";"):
clause = raw_clause.strip()
lower = clause.lower()
kind = ("spf" if lower.startswith("spf=") else "dkim" if lower.startswith("dkim=")
else "dmarc" if lower.startswith("dmarc=") else None)
if kind is None:
continue
target: AuthResult = getattr(auth, kind)
if target.result != "none":
continue # first result wins
word = re.search(r"=\s*([a-z]+)\b", clause, re.I)
target.result = word.group(1).lower() if word else "unknown"
target.detail = clause
if kind == "spf":
target.domain = token(clause, "smtp.mailfrom") or token(clause, "mailfrom")
elif kind == "dkim":
target.domain = token(clause, "header.d") or token(clause, "header.i")
target.selector = token(clause, "header.s")
else:
target.domain = token(clause, "header.from")
policy = re.search(r"\bp=([a-z]+)", clause, re.I)
target.policy = policy.group(1).lower() if policy else None
return auth
def detect_anomalies(headers: List[Header], hops: List[Hop]) -> List[Anomaly]:
"""Classic spoofing checks: sender mismatch, Reply-To misdirection, bulk mailers, chain gaps."""
anomalies: List[Anomaly] = []
first = lambda name: next(iter(get_headers(headers, name)), "")
from_addr = extract_address(first("From"))
return_path = extract_address(first("Return-Path"))
if from_addr and return_path and from_addr.lower() != return_path.lower():
anomalies.append(Anomaly("from-return-path-mismatch", "critical",
f"Return-Path ({return_path}) does not match From ({from_addr}) — the envelope sender "
"differs from the displayed sender. Common in spoofing and mailing-list relay."))
reply_to = extract_address(first("Reply-To"))
if from_addr and reply_to and reply_to.lower() != from_addr.lower():
anomalies.append(Anomaly("reply-to-mismatch", "warning",
f"Reply-To ({reply_to}) differs from From ({from_addr}) — replies would go to a "
"different address than the visible sender."))
mailer = next(iter(get_headers(headers, "X-Mailer")), None)
if mailer is None:
mailer = next(iter(get_headers(headers, "User-Agent")), "")
hit = next((s for s in _SUSPICIOUS_MAILERS if s in mailer.lower()), None) if mailer else None
if mailer and hit:
anomalies.append(Anomaly("suspicious-mailer", "warning",
f'Mailer string "{mailer}" contains a suspicious token ("{hit}") often seen in bulk '
"sending tools."))
for i, hop in enumerate(hops):
if hop.timestamp is None:
label = hop.from_addr or hop.by or "unknown"
anomalies.append(Anomaly("hop-missing-timestamp", "info",
f"Hop {i + 1} ({label}) has no parseable timestamp — delay for this leg cannot "
"be computed."))
elif i > 0 and hops[i - 1].timestamp is not None:
delta = (hop.timestamp - hops[i - 1].timestamp).total_seconds()
if delta < 0:
anomalies.append(Anomaly("negative-delay", "warning",
f"Hop {i + 1} is timestamped {abs(delta):.1f}s BEFORE hop {i} — clock skew "
"between servers or a forged Received header."))
if not get_headers(headers, "Authentication-Results"):
anomalies.append(Anomaly("no-auth-results", "info",
"No Authentication-Results header found — SPF/DKIM/DMARC status cannot be verified "
"from this message."))
return anomalies
def parse_headers(raw: str) -> ParsedHeaders:
"""Parse raw email headers (RFC 5322): headers, chronological hops, auth verdicts, anomalies."""
headers = parse_header_lines(raw)
# Received headers are listed newest-first; parse bottom-up so hops[0] is the oldest.
hops = [parse_received(v) for v in reversed(get_headers(headers, "Received"))]
for i in range(1, len(hops)):
if hops[i].timestamp is not None and hops[i - 1].timestamp is not None:
hops[i].delay = (hops[i].timestamp - hops[i - 1].timestamp).total_seconds()
auth = parse_auth_results(get_headers(headers, "Authentication-Results"))
return ParsedHeaders(headers, hops, auth, detect_anomalies(headers, hops))
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →