Before I send anything to a list of addresses from a CRM export or a sign-up form, I want to drop the ones that cannot possibly receive mail. Dead domains, typos like gmial.com and throwaway inboxes are the usual suspects, and every bounce they cause hurts the sender reputation of the domain you send from.
You can catch most of them without sending a single email. All you need is DNS, and a short Python script with no dependencies outside the standard library.
What DNS can tell you about an address
For jane@example.org, everything interesting is in the domain part:
-
Does the domain exist? If DNS answers
NXDOMAIN, nobody can receive mail there. - Does it have MX records? MX records name the mail servers for a domain. If they exist, the domain at least accepts mail.
-
Is it a null MX? RFC 7505 lets a domain publish
MX 0 .to say "this domain accepts no mail".example.comdoes exactly that. Treat it as invalid. - No MX, but an A record? RFC 5321 says senders should then try the A record. It sometimes works, but it is often a parked or typo domain, so I mark it as risky rather than valid.
On top of DNS, two cheap local checks help: a list of known disposable domains, and role addresses like info@ or sales@, which are fine for B2B lists but you may not want for personal outreach.
What DNS cannot tell you is whether a specific mailbox exists on a domain that accepts mail. That needs an SMTP handshake, which is slower, often blocked, and outside the scope of this post.
The script
It reads one address per line, removes duplicates, checks the domains in parallel and writes a CSV to stdout. It uses Google's public DNS-over-HTTPS JSON endpoint, so you do not need dnspython and it works from networks that block plain port 53.
import csv, difflib, json, re, sys, urllib.parse, urllib.request
from concurrent.futures import ThreadPoolExecutor
DOH = "https://dns.google/resolve"
SYNTAX = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$")
DISPOSABLE = {"mailinator.com", "guerrillamail.com", "10minutemail.com", "yopmail.com",
"temp-mail.org", "trashmail.com", "sharklasers.com", "getnada.com"}
ROLES = {"info", "admin", "support", "sales", "contact", "hello", "office", "noreply", "no-reply"}
POPULAR = ["gmail.com", "yahoo.com", "outlook.com", "hotmail.com", "icloud.com", "proton.me"]
def dns(name, rtype):
url = DOH + "?" + urllib.parse.urlencode({"name": name, "type": rtype})
with urllib.request.urlopen(url, timeout=10) as r:
data = json.load(r)
# Status 0 = NOERROR, 3 = NXDOMAIN (domain does not exist)
return data["Status"], [a["data"] for a in data.get("Answer", []) if a["type"] == {"MX": 15, "A": 1}[rtype]]
def check(email):
email = email.strip()
row = {"email": email, "verdict": "", "reason": "", "suggestion": "", "role": False}
if not SYNTAX.match(email):
return {**row, "verdict": "invalid", "reason": "bad syntax"}
local, domain = email.rsplit("@", 1)
domain = domain.lower()
row["role"] = local.lower() in ROLES
close = difflib.get_close_matches(domain, POPULAR, n=1, cutoff=0.8)
if close and close[0] != domain:
row["suggestion"] = f"{local}@{close[0]}"
if domain in DISPOSABLE:
return {**row, "verdict": "risky", "reason": "disposable domain"}
try:
status, mx = dns(domain, "MX")
if status == 3:
return {**row, "verdict": "invalid", "reason": "domain does not exist"}
if mx and all(m.split()[-1] == "." for m in mx):
return {**row, "verdict": "invalid", "reason": "null MX (domain accepts no mail)"}
if mx:
return {**row, "verdict": "valid", "reason": "has MX"}
_, a = dns(domain, "A") # RFC 5321: no MX means mail goes to the A record
if a:
return {**row, "verdict": "risky", "reason": "no MX, A record fallback"}
return {**row, "verdict": "invalid", "reason": "no MX and no A record"}
except Exception as e:
return {**row, "verdict": "unknown", "reason": f"DNS error: {e}"}
if __name__ == "__main__":
emails = list(dict.fromkeys(l.strip() for l in open(sys.argv[1]) if l.strip()))
with ThreadPoolExecutor(max_workers=8) as pool:
rows = list(pool.map(check, emails))
w = csv.DictWriter(sys.stdout, fieldnames=rows[0].keys())
w.writeheader()
w.writerows(rows)
A few notes on the choices:
- The syntax regex is deliberately loose. Strict RFC 5322 parsing rejects real addresses more often than it catches bad ones. Its only job is to throw out obvious junk before spending a DNS query on it.
-
Statusin the DoH response is the DNS response code:0is NOERROR and3is NXDOMAIN. - The disposable list here is a tiny sample. For real use, load a maintained list such as disposable-email-domains into the set.
-
difflib.get_close_matchesis enough for typo suggestions against a handful of big providers. It only suggests, it never rewrites the address.
Running it
Put a few addresses in emails.txt:
jane@github.com
sales@stripe.com
bob@gmial.com
hello@example.com
someone@mailinator.com
not-an-email
x@this-domain-does-not-exist-tinyrex-test.com
jane@github.com
Then run:
python3 check_emails.py emails.txt > checked.csv
This is the output I got today:
email,verdict,reason,suggestion,role
jane@github.com,valid,has MX,,False
sales@stripe.com,valid,has MX,,True
bob@gmial.com,risky,"no MX, A record fallback",bob@gmail.com,False
hello@example.com,invalid,null MX (domain accepts no mail),,True
someone@mailinator.com,risky,disposable domain,,False
not-an-email,invalid,bad syntax,,False
x@this-domain-does-not-exist-tinyrex-test.com,invalid,domain does not exist,,False
The duplicate jane@github.com was dropped before any lookup. gmial.com is a good example of why "no MX, has A record" should not count as valid: the domain resolves, but it is not where Bob reads his mail, and the suggestion column points at the likely fix.
Making it faster on big lists
Most lists repeat the same few domains (gmail.com alone can be a third of a consumer list). If you check tens of thousands of addresses, cache the DNS result per domain, for example with functools.lru_cache on a helper that takes only the domain. That turns 50,000 lookups into a few thousand. Keep the worker count modest so the public resolver does not rate-limit you.
If you would rather not run it yourself
I maintain a hosted version of this as an Apify actor, Email Validator - Bulk MX, Disposable, Role & Typo Check. It does the same DNS checks plus SPF and DMARC lookups, uses a full disposable list, and charges per address that gets a verdict, while bad syntax, duplicates and DNS errors are free. The script above is enough for most one-off cleanups, though.
Disclosure: I built and maintain the Email Validator actor linked above.
Top comments (0)