validate email in python

How to validate email in python?

How to write a Python program to determine whether or not a string is a valid email address?

You can achieve this by using a simple regular expression or a module.

validate email in python by using regular expression

A Regular Expression (RegEx) is a specific sequence of letters that searches for a string or set of strings using a search pattern.

It can match a pattern to detect the presence or absence of text, and it can also divide a pattern into one or more sub-patterns.

Python has a re package that allows you to utilize regex in Python. Its main purpose is to perform a search using a regular expression and a string. It either returns the first match or none at all in this case.

for example

# code example of re in python, validate email in python
import re 
s = 'Infopediya, Learn to code'
 
match = re.search(r'code', s)
 
print('Start Index:', match.start())
print('End Index:', match.end())
# Start Index: 21
# End Index: 25
#

The search() method of the re module is used in this program. So, let’s have a look at the description.
re.search() gives you a result. If the pattern does not match, return None; otherwise, return re.MatchObject, which provides information about the matching part of the string.

This method is more suited for checking a regular expression than extracting data because it ends after the first match.

# import re module to validate email in python
import re
# Make a regular expression, for validating an Email
regex = r'\b[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
# Define a function for, for validating an Email
def validate_email(email):
	if(re.fullmatch(regex, email)):
		print("Valid Email")
	else:
		print("Invalid Email")
if __name__ == '__main__':
 
    # Enter the email
    email = "[email protected]"
 
    # calling run function
    validate_email(email)
How to validate email in python?
How to validate email in python?

validate email in python using a library (email-validator)

This library checks to see if a string is in the format [email protected] This is the type of validation you’d want for a website’s email-based login form.

Best Features:

Checks if an email address has the correct syntax, which is useful for login forms and other user identification purposes.


When validation fails, it displays pleasant error messages (appropriate to show to end-users).


The library is not intended to validate the line in an email message (e.g. My Name), for which the flanker is better suited. And because this library does not allow obsolete forms of email addresses, you should use pyIsEmail instead if you need stringent validation against the email specs.

Installation

# install email-validator
pip install email-validator

Usage

You could perform something like this to validate a user’s email address before creating a user account:

# how to use email_validator?
from email_validator import validate_email, EmailNotValidError
email = "[email protected]"
try:
  # Validate.
  valid = validate_email(email)
  # Update with the normalized form.
  email = valid.email
except EmailNotValidError as e:
  # email is not valid, exception message is human-readable
  print(str(e))
#

This checks the address and returns it in its normalized form. You should always normalize before checking if an address is in your database, and you should always normalize before checking if an address is in your database.