Validate an email address in Python

Check that an email address looks right, and know what that check does not tell you.

To validate an email in Python you check its shape with a short regular expression, then send a confirmation message to find out whether it is real. The standard library covers the first part.

The short answer

import re

EMAIL = re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+")


def is_email(value):
    return isinstance(value, str) and EMAIL.fullmatch(value) is not None


is_email("[email protected]")    # True
is_email("ada@example")        # False
is_email("ada @example.com")   # False
is_email("ada@@example.com")   # False

The pattern reads: something, an @, something, a dot, something, with no spaces and no second @ anywhere. That catches typos and pasted junk, which is what a format check is for.

Use fullmatch, not match. With match and a $ anchor, "[email protected]\n" passes, because $ is happy to match just before a trailing newline. fullmatch has to consume the whole string.

Python email regex: why there is no perfect one

The rules for what counts as an address (RFC 5322) allow quoted local parts, comments in brackets and characters most people have never seen in an address. A regex that follows the standard to the letter runs to thousands of characters, and it still accepts addresses no mail provider would create.

Going the other way is worse. A strict pattern that only allows letters, digits and a few symbols rejects real people, such as o'[email protected], or anyone with an accented name on an internationalised domain.

So the simple pattern is the better trade. It is loose on purpose:

is_email("o'[email protected]")   # True
is_email("[email protected]")                  # True, although no such domain can exist

A false "valid" costs you one bounced email. A false "invalid" costs you a customer who cannot sign up.

Validate an email address with parseaddr

email.utils.parseaddr comes up in a lot of answers. It splits a header-style address into a display name and the address itself:

from email.utils import parseaddr

parseaddr("Ada Lovelace <[email protected]>")   # ('Ada Lovelace', '[email protected]')
parseaddr("ada@example")                      # ('', 'ada@example')
parseaddr("not an email")                     # ('', 'not')
parseaddr("ada@")                             # ('', '')

It is a parser, not a validator. It returns ('', '') for some broken input, but it accepts ada@example and turns not an email into not. Use it to pull the address out of a To: or From: header, then run that address through is_email:

name, address = parseaddr("Ada Lovelace <[email protected]>")
is_email(address)   # True

Format check or real mailbox?

Everything above answers one question: does this string have the shape of an email address? It says nothing about whether the domain exists, whether it accepts mail, or whether the person typing owns the mailbox.

You can get a little closer by looking up the domain's MX records, which rules out [email protected]. You cannot go further from code. Mail servers will not reliably tell you whether a mailbox exists, because that is exactly what spammers want to know.

The only proof is a confirmation email with a link the person has to click. If the address matters, send one. The format check is there to catch typos before that point.

The email-validator package

If you want more than a regex, email-validator is the library to reach for. It follows the standards properly, handles international addresses, normalises the result and can check that the domain has mail records:

from email_validator import validate_email, EmailNotValidError

try:
    result = validate_email("[email protected]", check_deliverability=True)
    email = result.normalized
except EmailNotValidError as e:
    print(e)

It needs pip install email-validator, and the deliverability check makes a DNS query, so it is slower and needs a network. For a signup form on a real product, it is worth it.

The shorter way with Nitro Validate

Email is rarely the only field. Nitro Validate checks it alongside everything else on the form and gives you every error at once:

from nitro_validator import Validator, ValidationError

validator = Validator()

rules = {
    "email": "required|email",
    "age": "required|integer|min:18",
}

try:
    validator.validate({"email": "ada@example", "age": "12"}, rules)
except ValidationError as e:
    print(e.errors)
#  'age': ['The age field must be at least 18.']}

validator.is_valid({"email": "[email protected]", "age": "36"}, rules)   # True

Its email rule is a format check like the one above, and a stricter one: ASCII letters, digits and ._%+- before the @, and a domain ending in at least two letters. That means it rejects o'[email protected] and international addresses. If your users might have those, use the looser pattern through the regex rule, or use email-validator. And if email is the only thing you are checking, the four-line function at the top is enough.

Common questions

Should I lowercase the address before saving it? Lowercase the domain, which is case-insensitive. The part before the @ is technically case-sensitive, though almost no provider treats it that way. Most apps lowercase the whole thing for lookups and accept the tiny risk.

Can I check that the mailbox exists without sending mail? Not reliably. Some servers answer an SMTP probe, many accept everything or refuse to say, and probing in bulk gets your IP blocked. Send a confirmation link.

Why does my regex reject addresses with a plus sign? Because the character class before the @ leaves + out. Plus addressing ([email protected]) is valid and common, so allow it.

This page uses Nitro Validate.

Validate data in one line. 51 built-in rules, zero dependencies, and pipe-string rules like required|email.

$ pip install nitro-validator