How to Validate Email Addresses in Python?

In this tutorial, I will explain how to validate email addresses in Python. As a Python developer working on a project for one of our USA clients, I came across a scenario where I needed to validate email addresses when dealing with user registration. I will help you to learn different methods to validate email addresses effectively with examples.

Methods for Email Validation in Python

There are multiple ways to validate email addresses in Python. Let’s explore a few commonly used methods:

1. Use Regular Expressions

One of the most popular approaches to validate email addresses is by using regular expressions (regex). Regular expressions allow us to define patterns that the email address should match. Here’s an example of how to use regex for email validation in Python:

import re

def is_valid_email(email):
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None

# Example usage
email1 = 'john.doe@example.com'
email2 = 'invalid.email'

print(is_valid_email(email1)) 
print(is_valid_email(email2))

Output:

True
False

I have executed the above example code and added the screenshot below.

Validate Email Addresses in Python

In this example, we define a function is_valid_email() that takes an email address as input. Inside the function, we use a regular expression pattern to match the email address. The pattern checks for the following criteria:

  • The email address should start with characters, digits, or specific symbols ([a-zA-Z0-9._%+-]+)
  • Followed by an “@” symbol
  • Followed by the domain name, which can contain characters, digits, and hyphens ([a-zA-Z0-9.-]+)
  • Followed by a dot (.) and at least two characters for the top-level domain (\.[a-zA-Z]{2,})

We use the re.match() function to check if the email address matches the specified pattern. If a match is found, the function returns True , indicating a valid email address. Otherwise, it returns False.

Check out Access Modifiers in Python

2. Use the email-validator Library

Another convenient way to validate email addresses in Python is by using the email-validator library source. This library simplifies the validation process and provides additional features. Here’s an example of how to use the email-validator library:

from email_validator import validate_email, EmailNotValidError

def is_valid_email(email):
    try:
        valid = validate_email(email)
        return True
    except EmailNotValidError:
        return False

# Example usage
email1 = 'sarah.johnson@example.com'
email2 = 'invalid.email'

print(is_valid_email(email1))
print(is_valid_email(email2)) 

Output:

True
False

I have executed the above example code and added the screenshot below.

How to Validate Email Addresses in Python

In this example, we import the validate_email function and EmailNotValidError exception from the email_validator library. We define the is_valid_email() function that takes an email address as input.

Inside the function, we use a try-except block to handle the validation. We call the validate_email() function with the provided email address. If the validation succeeds, it means the email address is valid, and we return True. If an EmailNotValidError exception is raised, it indicates an invalid email address, and we return False.

The email-validator library not only checks the syntax of the email address but also performs additional validation, such as checking the domain’s validity and DNS records.

Read How to Use Single and Double Quotes in Python?

3. Use the PyPi Validator Collection

The PyPi Validator Collection is another Python package that provides various validation utilities, including email validation. Here’s an example of how to use the PyPi Validator Collection for email validation:

from validator_collection import validators, errors

def is_valid_email(email):
    try:
        validators.email(email)
        return True
    except errors.InvalidEmailError:
        return False

# Example usage
email1 = 'michael.brown@example.com'
email2 = 'invalid.email'

print(is_valid_email(email1))
print(is_valid_email(email2)) 

Output:

True
False

I have executed the above example code and added the screenshot below.

Validate Email Addresses in Python PyPi Validator Collection

In this example, we import the validators and errors modules from the validator_collection package. We define the is_valid_email() function that takes an email address as input.

Inside the function, we use a try-except block to handle the validation. We call the validators.email() function with the provided email address. If the validation succeeds, it means the email address is valid, and we return True. If an InvalidEmailError exception is raised, it indicates an invalid email address, and we return False.

The PyPi Validator Collection offers a simple way to validate email addresses, along with other validation utilities.

Check out Python 3 vs Python 2

Best Practices for Email Validation in Python

When implementing email validation in your Python application, consider the following best practices:

  1. Use a reliable validation method: Choose a validation method that is well-tested and reliable. Regular expressions and reputable libraries like email-validator or PyPi Validator Collection are good options.
  2. Handle edge cases: Make sure to handle edge cases and uncommon email address formats. Consider the possibility of international email addresses or those with special characters.
  3. Provide informative error messages: When an email address fails validation, provide clear and informative error messages to the user. Guide them on how to enter a valid email address.
  4. Perform additional validation: Apart from syntax validation, consider additional checks, such as verifying the domain’s existence or using email verification services to ensure the email address is valid and deliverable.
  5. Sanitize user input: Always sanitize and validate user input to prevent security vulnerabilities, such as SQL injection or cross-site scripting (XSS) attacks.

Read Difference Between “is None” and “== None” in Python

Conclusion

In this tutorial, we explored different methods to validate email addresses in Python. I discussed importance of email validation , and methods for email validation in Python by using a regular expression, using the email-validator library, and using the PyPi validator collection. We also discussed some best practices for email validation in Python.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.