Python – Email Validation

Email Validation

In this tutorial, we will write a simple Python program that uses regular expressions to validate email addresses.

The pattern we validate is a basic pattern that allows email addresses with a-z and A-Z characters, 0-9 numbers, the special characters . _ % + - and an @ symbol, followed by a domain name and an extension(i.e .com, .org, .edu, etc).

Python Program

import re

def validate_email(email):
    # regular expression for an email address
    pattern = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
    # check if the pattern matches the email address
    match = pattern.search(email)
    return match

if __name__ == "__main__":
	email = input("Enter email address: ")
	match = validate_email(email)
        if match:
            print("Valid email address.")
        else:
            print("Invalid email address.")

Output 1

Enter email address: hello@gmail.com
Valid email address.

Output 2

Enter email address: @hellouser
Invalid email address.

What is in the program

  1. We have defined a function validate_email() that takes an email address (string) as an input and checks if it is a valid email or not and returns a boolean value.
  2. The regular expression pattern that is used to match the email address is defined at the top of the function using the re.compile() method.

This is a basic example of an email validation program. It may not be complete solution to validate any email address. But, this will give you a start.

In real-world situations, you may need to use more complex regular expressions to validate email addresses, depending on the specific requirements of your application.

Note

Remember that just validating an email address format is not a guarantee that the email address exists or that you will be able to send an email to it.

We should also check if the domain exists and if the email address has not bounced or marked as spam.

Summary

In this tutorial of Python Examples, we learned how to validate an email address.