Blog
Validate an email address in Python: email-validator, DNS, typos and a mailbox check
Validate email addresses in Python: check syntax and DNS with email-validator, catch typos and disposable domains, then confirm the mailbox with an API call.
Updated 2026-11-25
Validating an email address in Python takes four checks: the syntax, the domain's mail records, a look at the domain itself (typos, disposable services), and finally the mailbox. The email-validator package handles the first two in one call. A few lines of your own code cover typos and disposable domains. The mailbox needs a conversation with the recipient's mail server, which is where an API saves you the most work.
What each check proves
| Check | Tool | Proves | Cannot prove |
|---|---|---|---|
| Syntax | email-validator |
The address is well formed | That the domain exists |
| DNS | email-validator with check_deliverability |
The domain can receive mail | That this mailbox exists |
| Typo and disposable lists | Your code, or the API | The domain is likely mistyped or temporary | Anything about the person |
| Mailbox | An SMTP probe, or the API | The server accepts this exact mailbox | That someone reads it |
| Confirmation email | Your app | The person controls the inbox | Nothing more is needed |
How to verify an email address explains each step without code. This post is the Python version.
Install email-validator
pip install email-validator
The package pulls in dnspython for the DNS step and idna for international domain names. It supports internationalized addresses (RFC 6531), refuses forms that are legal in RFC 5322 but almost never used, such as quoted local parts and IP literals, and its error messages are written to be shown to users.
Check syntax and DNS
from email_validator import EmailNotValidError, EmailUndeliverableError, validate_email
def check_syntax_and_domain(address, check_dns=True):
try:
info = validate_email(address.strip(), check_deliverability=check_dns)
except EmailUndeliverableError as error:
return {"ok": False, "step": "dns", "message": str(error)}
except EmailNotValidError as error:
return {"ok": False, "step": "syntax", "message": str(error)}
return {"ok": True, "email": info.normalized, "domain": info.ascii_domain}
EmailUndeliverableError is a subclass of EmailNotValidError, so catch it first. Strip the input yourself: the library rejects surrounding spaces, and a pasted address often carries one.
We ran it with email-validator 2.4.0 and check_dns=False:
| Input | Result |
|---|---|
Jane.Doe@Gmail.com |
ok, Jane.Doe@gmail.com |
jane.@example.org |
An email address cannot have a period immediately before the @-sign. |
jane@localhost |
The part after the @-sign is not valid. It should have a period. |
"jane doe"@example.org |
Quoting the part before the @-sign is not allowed here. |
jane@[192.0.2.1] |
A bracketed IP address after the @-sign is not allowed here. |
jane@exämple.de |
ok, ASCII domain xn--exmple-cua.de |
jane@gmial.com |
ok |
Two lines deserve a comment. The domain was lowercased but the local part kept its case: RFC 5321 lets the server treat Jane.Doe and jane.doe as different mailboxes, so the library does not touch it. And jane@gmial.com passed, because nothing about it is malformed. Syntax cannot catch the most common mistake people make.
With check_dns=True, the library also queries the domain's MX records. A domain that does not exist, or that publishes a null MX record (RFC 7505), raises EmailUndeliverableError. Keep DNS on in a signup form, where one lookup per address is cheap, and off when you parse a large file, where you want to batch the network work.
Catch typos and disposable domains
A typo in a well-known domain is the cheapest error to fix, because you can offer the correction. difflib from the standard library is enough for a short list of common providers:
import difflib
from pathlib import Path
COMMON_DOMAINS = ["gmail.com", "yahoo.com", "hotmail.com", "outlook.com", "icloud.com", "aol.com", "proton.me"]
DISPOSABLE = {
line.strip().lower()
for line in Path("disposable_email_blocklist.conf").read_text().splitlines()
if line.strip() and not line.startswith("#")
}
def suggest(domain):
if domain in COMMON_DOMAINS:
return None
match = difflib.get_close_matches(domain, COMMON_DOMAINS, n=1, cutoff=0.8)
return match[0] if match else None
def is_disposable(domain):
labels = domain.split(".")
return any(".".join(labels[index:]) in DISPOSABLE for index in range(len(labels) - 1))
is_disposable also tests parent domains, so a listing for mailinator.com catches inbox.mailinator.com. The domain file comes from the community disposable-email-domains project on GitHub: download disposable_email_blocklist.conf, check its license for your use, and refresh it on a schedule, since temporary inbox services add domains all the time.
In our run, jane@gmial.com got the suggestion jane@gmail.com, jane@hotmial.com got jane@hotmail.com, and jane@yahoo.co got jane@yahoo.com. Both gmial.com and hotmial.com were also on the disposable list that day. A typo domain can be registered by anyone and can receive mail, so a syntax and DNS pass means nothing for it: one more reason to show the suggestion before saving.
Show the suggestion as a question ("Did you mean jane@gmail.com?") and let the person choose. Never correct an address silently: a small company can own a domain one letter away from a big one.
Disposable email detection covers when to block these domains and when to only flag them, and role-based email covers info@ and sales@.
Ask about the mailbox with an API
Everything so far runs on your machine. The last question, whether the mailbox exists, needs an SMTP conversation with the recipient's mail server on port 25. Most cloud providers block that port by default, large mailbox providers hide the answer, and catch-all domains accept every name. Check if an email exists without sending one shows the Python probe and why it breaks in production.
The Qelka email endpoint runs syntax, DNS, list and mailbox checks in one call:
import os
import requests
API_URL = "https://api.qelka.com/v1/email"
def verify_email(address, mode="full"):
try:
response = requests.post(
API_URL,
headers={"Authorization": f"Bearer {os.environ['QELKA_API_KEY']}"},
json={"email": address, "mode": mode},
timeout=15,
)
except requests.RequestException:
return {"decision": "accept_unchecked"}
if not response.ok:
return {"decision": "accept_unchecked"}
result = response.json()
status, reason = result["status"], result["reason"]
if status == "undeliverable":
return {"decision": "reject", "reason": reason, "did_you_mean": result["did_you_mean"]}
if status == "risky" and reason == "disposable":
return {"decision": "ask_for_another", "reason": reason}
return {"decision": "accept", "status": status, "reason": reason, "did_you_mean": result["did_you_mean"]}
print(verify_email("jane@gmial.com"))
The function fails open: a timeout or an error lets the signup through, and you can check later. An outage of a validation service should never block real users. The key stays on your server: a key in client code can be read and spent by anyone.
The fields you act on:
| Field | Values | Use it to |
|---|---|---|
status |
deliverable, undeliverable, risky, unknown |
Decide accept, reject or review |
reason |
accepted_email, mailbox_not_found, catch_all, disposable, greylisted... |
Explain the decision |
did_you_mean |
A corrected address or null | Offer the fix |
checks.catch_all |
true, false or null |
Know when acceptance proves nothing |
checks.disposable, checks.role, checks.free_provider |
booleans | Apply your own rules |
unknown is not a bad verdict. It means the server gave no clear answer: greylisting, a timeout, or a provider that hides mailbox status. Accept the address and let the confirmation email settle it. The email API reference lists every reason with what to do.
A check costs 1 credit in either mode, and checks that could not run on our side (smtp_unavailable, dns_error) are not billed. "mode": "fast" skips the mailbox step and answers without waiting for a mail server, which suits a field validated as the person types. A sk_test_ key returns simulated results and spends nothing: see test mode.
Wire it into a form
Run the local checks first, since they are free and instant, and call the API only for addresses that pass them.
def validate_signup_email(address):
local = check_syntax_and_domain(address)
if not local["ok"]:
return {"ok": False, "message": local["message"]}
domain = local["domain"]
typo = suggest(domain)
if typo:
return {"ok": False, "message": f"Did you mean {local['email'].split('@')[0]}@{typo}?"}
if is_disposable(domain):
return {"ok": False, "message": "Please use a permanent email address."}
remote = verify_email(local["email"])
if remote["decision"] == "reject":
suggestion = remote["did_you_mean"]
return {"ok": False, "message": f"Did you mean {suggestion}?" if suggestion else "This address cannot receive mail."}
if remote["decision"] == "ask_for_another":
return {"ok": False, "message": "Please use a permanent email address."}
return {"ok": True, "email": local["email"]}
In Django, call it from a form's clean_email and raise forms.ValidationError(result["message"]) when ok is false. In Flask or FastAPI, call it in the route before you create the user. The Python, Django, Flask and FastAPI pages show complete handlers.
Clean a list instead of a form
For a file of addresses, turn DNS off in email-validator, deduplicate on the normalized form, and send what remains to the batch endpoint, which takes up to 100 items per request:
import os
import requests
emails = ["jane@gmail.com", "jane.doe@mailinator.com", "bob@gmial.com"]
items = [{"type": "email", "email": address} for address in emails]
response = requests.post(
"https://api.qelka.com/v1/batch",
headers={"Authorization": f"Bearer {os.environ['QELKA_API_KEY']}"},
json={"items": items},
timeout=60,
)
for item, result in zip(items, response.json()["data"]):
if result["object"] == "error":
print(item["email"], "error", result["error"]["type"])
else:
print(item["email"], result["status"], result["reason"])
data[i] always answers items[i], and a failed item does not fail the batch. For tens of thousands of rows, upload a CSV to bulk verification instead, or follow the clean an email list guide.
Mistakes that cost the most
- Lowercasing the whole address. Lowercase the domain only, as
email-validatordoes. - Rejecting
unknown. You lose real customers whose provider hides mailbox status. - Probing port 25 from your web server. Your server's IP gets a reputation it did not need, and the port is usually closed anyway.
- Correcting typos silently. Ask, and keep what the person confirms.
- Skipping the confirmation email. It is the only proof that the person reads the inbox.
Try the free email verifier and email syntax checker on your own test addresses, and see the email verification API for pricing and limits.
Frequently asked questions
How do I validate an email address in Python?
email-validator and call validate_email(address). It checks the syntax against the email RFCs, normalizes the domain and, by default, looks up the domain in DNS to confirm it can receive mail. Catch EmailNotValidError to show the reason to the user. Store info.normalized. For the mailbox itself, call a verification API from your server, since a library cannot ask the mail server.Should I use a regex to validate email in Python?
jane@gmial.com. email-validator gives better syntax checks and readable error messages for the same effort. Neither can tell you whether the mailbox exists. See email validation regex for what a pattern can and cannot do.What does check_deliverability do in email-validator?
EmailUndeliverableError, a subclass of EmailNotValidError. It never contacts the mail server, so it cannot tell whether the mailbox exists. Turn it off with check_deliverability=False when you validate many addresses offline.Can Python check if an email mailbox exists?
smtplib, by asking the mail server about the address with RCPT TO and leaving before any message is sent. In practice it fails often: many networks block outbound port 25, large providers hide mailbox status, and catch-all domains accept every name. Check if an email exists without sending one shows the code and its limits. An API that runs the probe from prepared servers is the practical route.Keep going
- Free toolEmail verifierCheck syntax, domain, mail servers, disposable and role addresses, and ask the mail server whether the mailbox accepts mail.Try it
- APIEmail verificationSyntax, MX, mailbox check, disposable and role detection, typo suggestions and a score.See the API
- ArticleCheck if an email address exists without sending an email: an SMTP probe and its limitsCheck if an email address exists without sending mail: a working SMTP RCPT TO probe in Python, how to read the reply codes, detect catch-all, and why it breaks.Read
- ArticleEmail validation regex: what a pattern can check, and what it cannotWhat RFC 5321, RFC 5322 and RFC 6531 allow in an email address, a practical regex for forms, the cases it misses, and what to run after it.Read
Put this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time