Python Email Validation: What email-validator, DNS and an API Each Catch
For Python email validation, use the email-validator package with check_deliverability=False in the request path, store the normalized address it returns, and send that address to a verification API for everything syntax cannot see: whether the domain takes mail, whether it is a disposable provider, and what the recipient's mail server said. Skip the hand-written regex as a final verdict, and skip the smtplib RCPT script.
That advice is easy to give and harder to trust, so I ran eight addresses through four layers on Python 3.13 and kept the output. The table below is the result; the rest of the article is the code that produced it.
Eight addresses through four checks

Three results matter for the code that follows:
- A naive regex passed
user..name@example.org. The pattern^[\w.+-]+@[\w-]+\.[\w.-]+$allows consecutive dots, which RFC 5322 does not.email-validatorrejected it with a readable message. - The DNS check passed
user@gmial.com. On the day of the test, Cloudflare's resolver returned SERVFAIL for that domain and Google Public DNS returned no MX with an A record.email-validatorlets both through: the first because it treats resolver failure as "unknown", the second through the A-record fallback. The API flagged the typo and suggestedgmail.com. - The API rejected
josé@example.esthatemail-validatoraccepted by default. Internationalized local parts need SMTPUTF8 support end to end. If your stack does not have it, tell the library so the local check agrees with the rest of the pipeline.
Disposable domains and dead mailboxes passed every local layer. Both need data the library does not have: a maintained provider list and a conversation with the receiving server.
Syntax and normalization with email-validator
Install the library. The import name has an underscore; the package name has a hyphen.
pip install email-validator
from email_validator import EmailNotValidError, validate_email
for raw in ["John.Doe@Gmail.COM", "user..name@example.org", "josé@example.es"]:
try:
result = validate_email(raw, check_deliverability=False, allow_smtputf8=False)
print("ok ", result.normalized)
except EmailNotValidError as exc:
print("reject", raw, "->", exc)
Output:
ok John.Doe@gmail.com
reject user..name@example.org -> An email address cannot have two periods in a row.
reject josé@example.es -> Internationalized characters before the @-sign are not supported: 'é'.
Three things in that output matter for a signup form:
- Use
result.normalized, not the raw input. The domain is lowercased; the local part keeps its case, because the mailbox owner's server decides whether case matters. The email case sensitivity guide covers how to store and compare it. - The error message is safe to show users. It names the problem without echoing internals.
allow_smtputf8=Falseis a product decision. Leave it at the defaultTrueonly if your database, mail provider and downstream tools all handle SMTPUTF8 addresses. The SMTPUTF8 developer guide explains what has to support it. Internationalized domains still work with the flag off:user@bücher.depasses andresult.ascii_emailreturnsuser@xn--bcher-kva.de.
One trap from real support threads: do not name your own script email_validator.py. Python imports your file instead of the package, and the error looks like a broken install:
ImportError: cannot import name 'validate_email' from 'email_validator' (consider renaming '/home/you/project/email_validator.py' if it has the same name as a library you intended to import)
Pydantic EmailStr is the same check
Pydantic's EmailStr calls email-validator under the hood (install it with pip install "pydantic[email]"). It normalizes and checks syntax, and that is all:
from pydantic import BaseModel, EmailStr
class Signup(BaseModel):
email: EmailStr
print(Signup(email="John.Doe@Gmail.COM").email) # normalized domain
print(Signup(email="user@example.com").email) # accepted: no DNS check
John.Doe@gmail.com
user@example.com
example.com publishes a null MX record, so no mail to it can ever be delivered. EmailStr accepts it anyway, because it never touches DNS. That is the right default for a model field. It means a FastAPI or Pydantic model on its own is a format gate, not verification.
What check_deliverability does and does not prove
Set check_deliverability=True and the library looks up the domain's MX records, honours null MX (RFC 7505), and falls back to A/AAAA records as SMTP allows:
from email_validator import EmailNotValidError, validate_email
for raw in ["user@example.com", "user@no-such-domain-q7x2k.com", "user@gmial.com"]:
try:
result = validate_email(raw, check_deliverability=True, timeout=5)
print("ok ", result.normalized, getattr(result, "mx", "no MX data"))
except EmailNotValidError as exc:
print("reject", raw, "->", exc)
reject user@example.com -> The domain name example.com does not accept email.
reject user@no-such-domain-q7x2k.com -> The domain name no-such-domain-q7x2k.com does not exist.
ok user@gmial.com no MX data
The last line is the catch. When the resolver fails or times out, email-validator returns success and leaves out the mx attribute instead of raising. Its source says so directly: it allows the domain through when all nameservers fail. That is a reasonable choice for a library, since a DNS outage should not lock users out, but it means "no exception" does not mean "this domain routes mail".
The check also depends on the resolver your code runs against. In the container I used for these tests, the system resolver returned no MX answers at all, even for gmail.com. email-validator fell back to A records and passed user@example.com, null MX and all. The results above come from routing the same code through a working resolver. Run your tests on the network your production code uses.
If you need to tell those cases apart, ask dnspython yourself. This function returns one of six states instead of pass/fail:
import dns.exception
import dns.resolver
def mail_routing(domain: str, timeout: float = 5.0) -> str:
"""Return 'mx', 'null_mx', 'a_fallback', 'no_route', 'nxdomain' or 'dns_error'."""
resolver = dns.resolver.Resolver()
resolver.lifetime = timeout
try:
answer = resolver.resolve(domain, "MX")
hosts = [str(r.exchange).rstrip(".") for r in answer]
if hosts == [""]: # RFC 7505: "0 ." means "this domain takes no mail"
return "null_mx"
return "mx"
except dns.resolver.NXDOMAIN:
return "nxdomain"
except dns.resolver.NoAnswer:
pass # no MX: RFC 5321 falls back to the A/AAAA record
except (dns.resolver.NoNameservers, dns.exception.Timeout):
return "dns_error" # resolver failure, not evidence about the address
for rdtype in ("A", "AAAA"):
try:
resolver.resolve(domain, rdtype)
return "a_fallback"
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
continue
except (dns.resolver.NoNameservers, dns.exception.Timeout):
return "dns_error"
return "no_route"
if __name__ == "__main__":
for d in ["gmail.com", "example.com", "no-such-domain-q7x2k.com", "gmial.com"]:
print(f"{d:28} {mail_routing(d)}")
gmail.com mx
example.com null_mx
no-such-domain-q7x2k.com nxdomain
gmial.com dns_error
Only null_mx, nxdomain and no_route are evidence against the address. dns_error is evidence about your resolver; retry it or send it to review. The null MX vs no MX guide explains why the empty-answer case falls back to A records instead of failing.
When a result looks wrong, check the domain from outside your network. Paste it into the free MX lookup tool and compare the DNS state with what your code reported:

null_mx result from the dnspython function.Why the smtplib script says yes to everything
A common next step is a script that connects to the MX host, sends MAIL FROM and RCPT TO, and treats a 250 reply as "the mailbox exists". People who try it report that every address on a domain comes back valid. Three things cause that, and a fourth makes it unsafe to run from an app server:
- Catch-all domains accept every recipient. A 250 from them says nothing about the mailbox. You only learn it is catch-all by also probing a random address. The catch-all domains guide covers how to handle that result.
- Greylisting and policy blocks return temporary codes. A 451 is not an invalid address; see SMTP greylisting.
- Cloud hosts block outbound port 25. Google Cloud blocks connections to port 25 outside your VPC, and AWS EC2 blocks port 25 to public addresses by default. From my test container the connection was refused immediately:
import smtplib
try:
smtplib.SMTP("gmail-smtp-in.l.google.com", 25, timeout=10)
except OSError as exc:
print(type(exc).__name__, exc)
ConnectionRefusedError [Errno 111] Connection refused
The fourth problem is reputation. Probing thousands of recipients from your sending IP looks like directory harvesting, and the blocklist recovery guide shows how long that takes to undo. The SMTP verification explainer walks through what a careful probe has to do instead.
One API call for routing, mailbox and provider signals
This is the function I would put in a signup handler. It runs the local check first, so malformed input never costs a credit, then sends the normalized address to POST /api/v1/verify. It needs httpx and email-validator:
pip install httpx email-validator
export EMAILVERIFIER_API_KEY=YOUR_API_KEY
import os
import httpx
from email_validator import EmailNotValidError, validate_email
API_URL = "https://emailverifier.dev/api/v1/verify"
TIMEOUT = httpx.Timeout(8.0, connect=3.0)
def check_signup_email(raw: str, client: httpx.Client) -> dict:
# 1. Local syntax check and normalization. No network, no credits.
try:
local = validate_email(raw, check_deliverability=False, allow_smtputf8=False)
except EmailNotValidError as exc:
return {"decision": "reject", "email": raw, "reason": str(exc)}
email = local.normalized
# 2. One server-side API call for routing, mailbox, and provider signals.
api_key = os.environ.get("EMAILVERIFIER_API_KEY")
headers = {"X-API-Key": api_key} if api_key else {} # no key = public demo, 10/hour
try:
response = client.post(API_URL, json={"email": email}, headers=headers, timeout=TIMEOUT)
except httpx.HTTPError as exc:
return {"decision": "review", "email": email, "reason": f"verifier unreachable: {exc.__class__.__name__}"}
if response.status_code == 401:
raise RuntimeError("EMAILVERIFIER_API_KEY is invalid") # config bug, not a user error
if response.status_code == 400:
return {"decision": "reject", "email": email, "reason": response.json().get("statusMessage")}
if response.status_code != 200: # 402 no credits, 429 rate limit, 5xx
return {"decision": "review", "email": email, "reason": f"verifier returned {response.status_code}"}
result = response.json()
if result["suggestion"]: # likely typo: ask before rejecting
decision = "suggest"
else:
decision = {"allow": "accept", "review": "review", "block": "reject"}[result["action"]]
return {
"decision": decision,
"email": email,
"status": result["status"],
"signals": result["signals"],
"suggestion": result["suggestion"],
}
if __name__ == "__main__":
import sys
with httpx.Client() as client:
for address in sys.argv[1:]:
print(check_signup_email(address, client))
Each branch maps one failure to one outcome:
- Local syntax failure: reject with the library's message. No request is sent.
suggestionpresent: show "Did you mean …?" before rejecting. The typo correction guide covers the UI.actionofallow,revieworblock: map straight to accept, review and reject.reviewis how catch-all and inconclusive results arrive; keep those users moving with a confirmation email instead of a hard error.- 401: raise. A bad key is a deploy bug and should page someone, not reject a customer.
- 402, 429, 5xx and timeouts: review, not reject. The verifier being unavailable is not evidence against the address.
Run it against a few addresses. Without a key, the endpoint runs as a public demo limited to 10 requests per hour:
python verify_signup.py "user..name@example.org" "User@GMIAL.com" "zq-test-7731-nobody@gmail.com"
{'decision': 'reject', 'email': 'user..name@example.org', 'reason': 'An email address cannot have two periods in a row.'}
{'decision': 'suggest', 'email': 'User@gmial.com', 'status': 'risky', 'signals': ['disposable_address', 'possible_typo'], 'suggestion': 'User@gmail.com'}
{'decision': 'reject', 'email': 'zq-test-7731-nobody@gmail.com', 'status': 'undeliverable', 'signals': ['free_provider', 'mailbox_rejected'], 'suggestion': None}
The first address never left the process. The second got a correction instead of a dead end. The third was rejected because Gmail's server refused the recipient, which no amount of local checking could have told you. The full list of status, action and signals values is in the API docs, and the API results guide covers what to log for each.
Test the policy without spending credits
The client is a parameter, so tests can swap in httpx.MockTransport and pin every branch without a network call. A few of the eleven tests:
import httpx
import pytest
from verify_signup import check_signup_email
def client_returning(status, body=None, exc=None):
def handler(request):
if exc:
raise exc
return httpx.Response(status, json=body)
return httpx.Client(transport=httpx.MockTransport(handler))
def test_bad_syntax_never_calls_the_api():
client = client_returning(500, exc=AssertionError("API was called"))
assert check_signup_email("user..name@example.org", client)["decision"] == "reject"
@pytest.mark.parametrize("status", [402, 429, 503])
def test_verifier_trouble_is_not_a_user_error(status):
assert check_signup_email("user@gmail.com", client_returning(status, {}))["decision"] == "review"
def test_bad_key_fails_loudly():
with pytest.raises(RuntimeError):
check_signup_email("user@gmail.com", client_returning(401, {"statusCode": 401}))
def test_typo_suggestion_is_offered_before_rejecting():
body = {"email": "user@gmial.com", "status": "risky", "action": "block", "flagged": True,
"signals": ["disposable_address", "possible_typo"], "suggestion": "user@gmail.com"}
out = check_signup_email("user@gmial.com", client_returning(200, body))
assert out["decision"] == "suggest" and out["suggestion"] == "user@gmail.com"
pip install pytest
python -m pytest -q
........... [100%]
11 passed in 0.06s
The test that matters most is the one asserting that malformed input never reaches the API. It keeps both your credit balance and your error budget honest.
If you are wiring this into a framework, the FastAPI, Flask and Django REST Framework guides show the same policy inside a signup route. For a CSV of existing contacts, the bulk verification workflow is a better fit than a loop over this function. A new project comes with 1,000 free credits, and pricing after that is $0.50 per 1,000 checks.