Python: 3 Ways to Validate an Email Address

Updated: May 28, 2023 By: Khue Post a comment

Using a regular expression

The steps are:

  1. Import the re module for regular expression operations.
  2. Define a regular expression pattern for email validation.
  3. Use the re.match() function to check if the email matches the pattern.
  4. Handle the validation result accordingly.

The regular expression pattern we will use to validate email addresses is:

r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"

Code example:

import re

def validate_email(email):
    pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
    match = re.match(pattern, email)
    if match:
        print(f"{email} is a valid email address")
    else:
        print(f"{email} is NOT a valid email address")

validate_email("[email protected]")
validate_email("hello@slingacademy")

Output:

[email protected] is a valid email address
hello@slingacademy is NOT a valid email address

Regular expressions provide a flexible and efficient way to validate email addresses. The pattern can be customized for specific scenarios. The downside of this approach is that regular expressions may be complex and error-prone for beginners. The pattern might not cover all valid email formats, and some invalid emails may pass the validation.

Using the email-validator library

The email-validator library checks not only the syntax but also the deliverability of the email address by querying the domain name server (DNS). An email address, even though it’s in the right format, belongs to a bogus domain that won’t pass the check.

Since email-validator is a third-party library, you need to install it first:

pip install email-validator

Then use it like so:

from email_validator import validate_email, EmailNotValidError

try:
    validate_email("[email protected]")
    print("Email is valid")
except EmailNotValidError as e:
    print(str(e))

Output:

Email is valid

In the example above, we used a try...catch block because the validate_email() function can raise an exception if the email address is invalid or cannot be verified. An exception is an error that occurs during the execution of a program that disrupts the normal flow of the program. If an exception is not handled properly, it can cause the program to crash or terminate unexpectedly.

Using the pyIsEmail library

pyIsEmail is a third-party package that provides a comprehensive regex-based validation of email addresses. It also supports internationalized domain names and addresses. The name of the package is not easy to remember, but it works great.

Install:

pip install pyIsEmail

Example:

from pyisemail import is_email

# A valid email address
email1 = "[email protected]"
# An invalid email address (even though its pattern is ok)
email2 = "[email protected]"

# Check the syntax and deliverability of email1
result1 = is_email(email1, check_dns=True)
# Check the syntax and deliverability of email2
result2 = is_email(email2, check_dns=True)

# Print the results
print(result1)
print(result2)

Output:

True
False