Given a string that represents an email address, our task is to determine whether it follows the correct format. A valid email generally contains a username, the @ symbol, and a domain name. For example:
Valid: my.ownsite@our-earth.org, user123@gmail.com
Invalid: myownsite.com, user@@gmail.com
Below are different methods to check if email address is valid or not in Python.
Using email_validator
This method validates emails by applying strict rules defined in email standards. It checks the username, domain format, and whether the domain part is valid. If the email passes validation, it returns a normalized (cleaned) version of the email.
from email_validator import validate_email
email = "abcd8@gmail.com"
res = validate_email(email)
print("Valid Email")
Output
Valid Email
Explanation:
- validate_email(email): Verifies the email structure, domain, and returns a detailed result object when the email is valid.
- res: Stores validated information such as normalized email format.
- print("Valid Email"): Runs only if validation succeeds; validate_email() itself will raise an error if the email is invalid.
Using validators Package
This method checks whether the email fits the valid pattern using built-in validation logic. It automatically examines the username, @ symbol, and domain format together and returns True/False accordingly.
import validators
email = "my.ownsite@our-earth.org"
if validators.email(email):
print("Valid Email")
else:
print("Invalid Email")
Output
Valid Email
Explanation:
- validators.email(email): Returns the email itself if valid, otherwise False.
- if condition: Used to classify email as valid or invalid.
Using RegEx (re.fullmatch)
This method uses a regex pattern to match the entire email string. It validates each part ensuring the full email follows allowed character rules.
import re
regex = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,7}"
email = "my.ownsite@our-earth.org"
print("Valid Email" if re.fullmatch(regex, email) else "Invalid Email")
email = "abc36.com"
print("Valid Email" if re.fullmatch(regex, email) else "Invalid Email")
Output
Valid Email Invalid Email
Explanation:
- re.fullmatch(regex, email): Ensures the entire string matches the pattern.
- [A-Za-z0-9._%+-]+ allowed characters in username, @ mandatory separator, [A-Za-z0-9.-]+ domain name and \.[A-Za-z]{2,7} extension like .com, .org
Using re.match
This method checks whether the email starts with a valid email pattern. It does not force the entire string to match, but still validates the username, @, and domain portion from the beginning.
import re
email = "my.ownsite@our-earth.org"
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
valid = re.match(pattern, email)
print("Valid email." if valid else "Invalid email.")
Output
Valid email.
Explanation:
- re.match(): Checks pattern only from the beginning of the string.
- valid: Stores match object if found, otherwise None.