Email validation in Python
For most Python projects, validate emails with the email-validator package: it checks the syntax, normalises the address and can confirm the domain accepts mail. A short regex is fine for a quick sanity check. Neither can tell you whether the mailbox exists; that takes a verification API call.
Which check do you need?
Email validation in Python usually means one of three checks. Syntax: is the string shaped like an email? Domain: does the domain publish mail servers? Mailbox: will mail to this exact address be accepted? A regex covers the first, email-validator covers the first two, and only a check against the mail server covers the third.
One trap in the standard library: email.utils.parseaddr splits a display name from an address in a header like Dana <dana@example.com>. It doesn't validate anything and will return strings that aren't addresses at all, so don't use it as a check.
A quick regex check
Use re.fullmatch, not re.match: match only anchors at the start, so dana@gmail.com junk would pass. Keep the pattern loose on purpose. Hand-written strict patterns tend to reject real addresses, like ones with a + tag or a long new top-level domain.
import re
# One @, no whitespace, at least one dot after the @. Deliberately loose.
EMAIL_RE = re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+")
def looks_like_email(value: str) -> bool:
value = value.strip()
return len(value) <= 254 and EMAIL_RE.fullmatch(value) is not None
looks_like_email("dana.reyes@gmail.com") # True
looks_like_email("dana.reyes+news@gmail.com") # True
looks_like_email("dana.reyes@gmail") # False: no dot in the domain
looks_like_email("dana reyes@gmail.com") # False: contains a spaceSyntax and domain checks with email-validator
email-validator checks the address against the email RFCs, raises exceptions with messages you can show users, and with check_deliverability=True looks up the domain's DNS to confirm it can receive mail. Reuse one caching resolver when you validate many addresses; it also lets you set a shorter DNS timeout. Skip the DNS check where speed matters more than accuracy, such as on a login form.
# pip install email-validator
from email_validator import (
EmailNotValidError,
EmailUndeliverableError,
caching_resolver,
validate_email,
)
resolver = caching_resolver(timeout=5)
def clean_email(value: str) -> str:
"""Return the normalised address, or raise ValueError with a message for the user."""
try:
info = validate_email(value, check_deliverability=True, dns_resolver=resolver)
except EmailUndeliverableError as e: # subclass of EmailNotValidError, so catch it first
raise ValueError("That domain doesn't accept email. Check for typos.") from e
except EmailNotValidError as e:
raise ValueError(str(e)) from e
return info.normalized
clean_email("Dana.Reyes@GMAIL.com") # 'Dana.Reyes@gmail.com': the domain is lowercased
clean_email("dana.reyes@gmial.con") # ValueError: that domain doesn't accept email
clean_email("dana..reyes@gmail.com") # ValueError: two periods in a rowWhat each approach catches
The rows at the bottom are why addresses that pass validation still bounce.
| Problem | Regex | email-validator | Verification API |
|---|---|---|---|
| Missing @, spaces, stray characters | Yes | Yes | Yes |
| Bad dots, over-long parts, invalid domain syntax | Partly | Yes | Yes |
| Domain doesn't exist or has no mail servers | No | Yes, with the DNS check | Yes |
| Mailbox doesn't exist | No | No | Yes |
| Catch-all domain: is anyone really there? | No | No | Yes, with MailVet |
| Disposable inbox | No | No | Flagged |
| Role address such as info@ or sales@ | No | No | Flagged |
| Typo at a real domain (jhon@ for john@) | No | No | Only if that mailbox doesn't exist |
Check the mailbox with the MailVet API
The API waits up to 15 seconds, then returns HTTP 202 with status: "pending" for the slow catch-all checks, which finish within minutes. So keep the read timeout above 15 seconds, retry on 429, and poll the verification id until it's done. Polling like this suits scripts and background workers. In a web request, pass timeout=5 to the API and treat pending as accept now, check later.
import os
import time
import requests
API = "https://api.mailvet.app/v1"
session = requests.Session()
session.headers["Authorization"] = "Bearer " + os.environ["MAILVET_KEY"]
def _get(url: str, **kwargs) -> dict:
for _ in range(3):
# 5 s to connect, 20 s to read: the API can hold a request for up to 15 s
r = session.get(url, timeout=(5, 20), **kwargs)
if r.status_code == 429:
time.sleep(float(r.headers.get("Retry-After", 1)))
continue
r.raise_for_status() # 401 bad key, 402 out of credits, 5xx
return r.json()
raise RuntimeError("still rate limited after 3 attempts")
def verify(email: str, max_wait: float = 420) -> dict:
v = _get(f"{API}/verify", params={"email": email})
deadline = time.monotonic() + max_wait
delay = 5.0
while v["status"] == "pending" and time.monotonic() < deadline:
time.sleep(delay)
delay = min(delay * 2, 60)
v = _get(f"{API}/verify/{v['id']}")
return v
v = verify("dana.reyes@northwind.example")
if v["status"] == "pending":
print("still running; it will reach your webhook if you set one:", v["id"])
elif v["result"] == "deliverable":
print("send", v["reason"], v["score"]) # accepted or catch_all_verified
elif v["result"] == "undeliverable":
print("remove", v["reason"]) # mailbox_not_found, invalid_domain, ...
else:
print("hold", v["result"], v["reason"], v["credits_charged"]) # risky, or unknown (free)Verifying a whole list? Send it as one bulk job
For more than a few hundred addresses, a bulk job beats a loop: duplicates and malformed addresses are removed before any credit is spent, and the slow catch-all checks are handled for you. In production, set a webhook and wait for bulk.completed instead of polling. Reference in /docs/bulk.
import os
import time
from pathlib import Path
import requests
API = "https://api.mailvet.app/v1"
HEADERS = {"Authorization": "Bearer " + os.environ["MAILVET_KEY"]}
emails = Path("leads.txt").read_text().split() # one address per line
resp = requests.post(f"{API}/bulk", json={"emails": emails}, headers=HEADERS, timeout=60)
resp.raise_for_status()
job = resp.json()
print(f"{job['total']} to verify, {job['duplicates_removed']} duplicates removed")
while True:
s = requests.get(f"{API}/bulk/{job['id']}", headers=HEADERS, timeout=20).json()
if s["status"] == "done":
break
if s["status"] not in ("queued", "running"):
raise RuntimeError(f"bulk job stopped with status {s['status']}")
print(f"{s.get('processed', 0)}/{s['total']}")
time.sleep(30)
r = requests.get(
f"{API}/bulk/{job['id']}/results",
params={"format": "csv", "result": "deliverable"},
headers=HEADERS,
timeout=120,
)
r.raise_for_status()
Path("deliverable.csv").write_bytes(r.content)Python email validation questions
What is the best way to validate an email address in Python?
Use the email-validator package for syntax and, optionally, a DNS check that the domain receives mail. If you need to know whether the mailbox exists, add a verification API call after it.
Is there a regex that matches every valid email address?
Not one you'd want to maintain. The RFCs allow quoted strings, comments and other forms people never type into a form. A loose regex plus a real verification check is more accurate than a strict pattern on its own.
Does email-validator check that the mailbox exists?
No. With check_deliverability on, it checks the domain's DNS records. It never contacts the mail server, so it can't tell a real mailbox from a dead one at a working domain.
Can I check if an email exists with smtplib?
Technically you can open an SMTP connection and send RCPT TO, but outbound port 25 is blocked on most clouds, catch-all domains accept every address, and repeated probes can get your IP blocklisted. A verification API does this part for you.
Verify mailboxes, not just syntax
Get an API key with 100 free credits. Test keys (mv_test_) never use credits, so your tests can call the real endpoint.
Related
- API quickstart
- Email verification API
- Bulk email verifier
- Node.js email validation
- How to verify an email
Last updated November 13, 2026