English Help Legal Sign Up Log In

Build a lightweight email syntax checker in Python

Scraped directories, conference attendee exports and decade-old CRM dumps all arrive with the same problem: addresses that look plausible and bounce anyway. Plenty of those failures are syntax errors rather than reputation problems, and catching them costs nothing more than a regular expression and a few lines of Python. Learn more about Pourquoi Les Disputes Sur Le Choix Du Film Revelent Tout De Votre Couple.

That matters more in Australia than in most markets. Small operators in Sydney and Melbourne run their own newsletters, keep subscriber lists in Mailchimp or Klaviyo, and often blend bought lists with sign-ups collected at a trade show in Brisbane or Perth. A batch with a fifteen percent soft failure rate drags the sending reputation of the whole domain down with it, and the ACMA rules under the Spam Act 2003 mean the consent and unsubscribe side of things needs to be airtight as well.

Why a syntax check earns its keep

Deliverability work in most outreach threads starts with reputation: SPF, DKIM, DMARC, warm-up, inbox placement. Syntax sits upstream of all of that. An address containing two at-signs, a space before the domain or a stray full stop is not a deliverability question at all, it is a typo, and no amount of warm-up will fix it.

A local checker also beats a paid verifier when the job is simple triage. Forum members regularly ask which validation platform to subscribe to, then discover they only needed a filter to keep obvious rubbish out of a form handler before anything hits a mailbox. Running a pattern match in-process is fast, free, works offline and tells you exactly which rule fired, which is handy when a client asks why a specific contact was rejected.

Treat the result as a first pass, not a verdict. A clean regex match says the address is shaped correctly; it says nothing about whether the mailbox exists, whether the domain accepts mail, or whether the person wants to hear from you.

Setting up a lean Python project

Keep it in one file. Python's standard library re module handles everything required for a syntax filter, so there is no reason to pull in a heavyweight package for a job this small. A virtual environment with a pinned Python 3.12 interpreter is plenty, and the whole script can sit next to the scraper that produced the data.

Write the checks as functions that accept a string and return a boolean or a reason code. Reason codes matter once the script feeds a spreadsheet back to a client: returning invalid: double dot in local part is far more useful than a bare False. Python's built-in email.utils.parseaddr is popular in these threads, and it is worth remembering that it is a parser rather than a validator, since it cheerfully returns something that looks like an address for input that is not one.

A quick sanity loop with a dozen hand-written cases catches most pattern mistakes before the script touches a real list:

CASES = {
    "sam.smith@example.com": True,
    "sam..smith@example.com": False,
    "sam smith@example.com": False,
    "sam@example": False,
    "sam@.com.au": False,
}

Building the core pattern

Split the problem into a local part and a domain, then define each separately. The dot-atom rules from RFC 5321 allow unquoted characters, dots between atoms, and no consecutive or trailing dots, which is where most naive patterns fail. A workable starting point looks like this:

import re

ADDRESS = re.compile(
    r"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+"
    r"(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*"
    r"@"
    r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+"
    r"[A-Za-z]{2,63}"
)

Use fullmatch rather than match with anchors, so a pattern cannot be satisfied by a valid substring buried inside junk. Skip re.IGNORECASE unless you want to accept uppercase local parts that real servers will reject, and avoid nested quantifiers such as (a+)+, which invite catastrophic backtracking on long hostile inputs.

Add the length rules that a pattern cannot express:

def syntax_ok(address: str) -> bool:
    candidate = address.strip()
    if len(candidate) > 254:
        return False
    local, sep, _domain = candidate.rpartition("@")
    if not sep or len(local) > 64:
        return False
    return ADDRESS.fullmatch(candidate) is not None

Edge cases that break naive checks

Quoted local parts, comments and plus addressing all pass or fail depending on how strict you want to be. john+newsletter@example.com is valid and common, so the pattern above accepts it, but a quoted string such as "john doe"@example.com is legal RFC 5321 syntax that almost no scraped list contains. Decide deliberately whether to accept them, then document the choice.

Unicode domains need converting before matching. Punycode gives a label such as xn--bcher-kva.de, which fits the pattern, while the raw Unicode form does not. The same goes for the local part in internationalised addresses, where the accepted practice is punycode conversion or SMTPUTF8 support on the sending side. Domain labels have their own ceiling of 63 characters, and the whole address is capped at 254, so check both rather than trusting the pattern alone.

Also decide how you treat addresses that parse correctly but are useless commercially. Role inboxes such as postmaster@ or abuse@ are valid and often required by policy, so flag them instead of dropping them. Disposable providers such as Mailinator and Guerrilla Mail are equally valid, and belong in a separate category that gets routed to a verification or campaign exclusion list.

From syntax to deliverability signals

Once the syntax filter runs clean, the next layer is domain-level. An MX lookup through dns.resolver from dnspython tells you whether a domain receives mail at all, and that single check removes a large share of dead addresses. A DMARC policy published by the domain tells you whether the sender side of a DMARC alignment check is even possible, and SPF records tell you which hosts are allowed to send on its behalf.

Typos are worth a separate pass because they are invisible to a syntax check. gmial.com, hotnail.com.au and a stray .com.au versus .au are all syntactically perfect. A fuzzy comparison against a set of known providers, weighted so that a .com.au variant is compared with .com.au entries first, catches most of them without guessing.

Catch-all domains are harder. Some mail hosts answer for every address at a domain, so an SMTP probe returns success for a mailbox that does not exist. That is a signal to treat the domain with suspicion rather than trust the response. None of these checks replace a real verification service, but stacking them in front of one saves API credits and shortens the feedback loop.

Checks to run before you upload a list

Common syntax failures worth catching first:

  • Missing, duplicated or misplaced at-signs, and spaces around the separator
  • Consecutive dots, or a leading or trailing dot in the local part
  • Domains with no dot, empty labels, or labels longer than 63 characters
  • Non-ASCII characters that need punycode conversion before matching
  • Addresses longer than 254 characters, or local parts longer than 64

Signals worth checking separately:

  • Missing MX records for the domain
  • Role or disposable inboxes that should be flagged rather than mailed
  • Catch-all domains that accept any local part
  • SPF, DKIM or DMARC gaps revealed during a test send
  • Likely typos that resolve to a real mailbox under a different spelling

Forum threads wander into everything, and one classic diversion explains how choosing the film exposes the dynamics of a relationship. That is a decent analogy for list hygiene: one shared decision, endless arguments. Picking a single validation approach, documenting its limits and reviewing results against a handful of Australian examples such as .com.au registries and.auDA whois rules is what keeps the debate from eating the afternoon.