Register Login

Validate Email Addresses in Python?

Validating email addresses is a very crucial factor. Whether someone is making a registration form for a website or just felt the need to filter all invalid emails from the mailing list. Either way, it is mandatory to execute the email validation process.

In this article, we'll look at various ways one can validate email addresses in Python.

What is a valid email address?

A valid email comprises a string where the @ symbol (This symbol is read aloud as 'at'.) splits it into two parts:

  1.  "personal_info" and
  2.  domain,

For example, personal_info@companydomain.

The personal_info part can have a length up to 64 characters long, and for the domain up to 253 characters.
If an email address meets the below conditions, then it is valid:

  1. The format of the email address must be personal_info@company.domain format
  2. The personal_info part can contain the following ASCII characters:
  3. The uppercase and lowercase letters of English(A,....,Z), (a,.....,z)
  4. Numbers  (0-9).
  5. Characters: !, #, &, $, %, ', *, +, -, /, =, ?, ^, _, `, {, |, }, ~.
  6. Character . ( period, dot, or full stop) such that it will not come consecutively one after the other.
  7. The Company name can exclusively have upper and lowercase letters and numbers.
  8. The domain name can exclusively contain upper and lowercase letters.
  9. The highest length of the extension can be 3.

Below are examples of some valid and invalid email addresses:

Valid email addresses

  1. mysite@ourearth.com
  2. my.ownsite@ourearth.org
  3. mysite@you.me.net

Invalid email addresses

  1. thissite.google.com [ the symbol @ is missing]
  2. thuissite@.com.thy [ the TLD (Top Level Domain) cannot begin with a dot "." ]
  3. @thissite.me.net [ No character before @ ]
  4. thissite123@gmail.b [ here ".b" is an invalid TLD]
  5. thissite@.org.org [ TLD cannot begin with a dot "." ]
  6. .thissite@mysite.org [ an email should not start with "." ]
  7.  thissite()*@gmail.com [Only character, digit, underscore, and dash are valid ]
  8. thissite..1234@yahoo.com [double dots are not allowed]

Validate an email address using regular expression

Using regular expressions to validate an email address is the most favored and common choice. Below is the code to validate an email address using regular expression.

Code:

import re as r
# Making a regular expression to validate an Email
regexp = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

# Function to validate Email
def check(the_email):

	
	if(r.fullmatch(regexp, the_email)):
		print("The entered email is valid")

	else:
		print("The entered email is invalid")

# Driver Code
if __name__ == '__main__':

	# Enter the email
	the_email = "rahulpaul123@gmail.com"

	# calling run function
	check(the_email)

	the_email = "my.suraj@our-earth.org"
	check(the_email)
	
	the_email = "Hi.jdr@our-earth.org"
	check(the_email)

	the_email = "ankita326.com"
	check(the_email)
	the_email = "ankit404@.org"
	check(the_email)
	the_email = "Dipti404@.in"
	check(the_email)


Output:

Using Python re.match to validate an email address.

This function or method starts its searches from the beginning of the string if found returns the matched object. It returns none if the object gets matched in the middle of the string.

Code:

import re as r

# The function for validating an Email
def check_email(s):
	pat = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
	if r.match(pat,s):
		print("The entered email is valid")
	else:
		print("The entered email is invalid")

# Driver Code
if __name__ == '__main__':

	# Enter the email
	the_email = "rahulpaul123@gmail.com"

	# calling run function
	check_email(the_email)

	the_email = "my.suraj@our-earth.org"
	check_email(the_email)
	
	the_email = "Hi.jdr@our-earth.org"
	check_email(the_email)

	the_email = "ankita326.com"
	check_email(the_email)
	the_email = "ankit404@.org"
	check_email(the_email)
	the_email = "Dipti404@.in"
	check_email(the_email)

 

Output:

Validate an email address using email_validator

This library makes sure that the entered email or string is of the format personal_info@company.domain. Whenever the validation fails, it returns error messages.  

Code:

from email_validator import validate_email, EmailNotValidError

def check(email):
	try:
	# validate and get info
		v = validate_email(email)
		# replace with normalized form
		email = v["email"]
		print("True")
	except EmailNotValidError as e:
		# email is not valid, the exception message is human-readable
		print(str(e))

check("my.ownsite@our-earth.org")

check("ankitrai326.com")

Output:

Validate emails from a text file using Python

In the below code, the re.search method gets employed. Using this function, it is possible to validate multiple emails from the text file.

Code:

import re
a = open("a.txt", "r")
# c=a.readlines()
b = a.read()
c = b.split("\n")
for d in c:
	obj = re.search(r'[\w.]+\@[\w.]+', d)
	if obj:
		print("Valid Email")
	else:
		print("Invalid Email")

Output:

Conclusion:

Validation has a crucial role during the creation of a website or app. An email address is a string separated by the symbol '@'. The email address to validate must meet some conditions (mentioned above). This article describes four ways to validate an email:

  1. Using regular expression
  2. Using Python re.match
  3. Using Python email_validator
  4. Validate email from a text file using Python


×