Open In App

Check if email address valid or not in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a string, write a Python program to check if the string is a valid email address or not. An email is a string (a subset of ASCII characters) separated into two parts by @ symbol, a “personal_info” and a domain, that is personal_info@domain.

Examples:

Input:  ankitrai326@gmail.com
Output: Valid Email

Input: my.ownsite@ourearth.org
Output: Valid Email

Input: ankitrai326.com
Output: Invalid Email

Method 1: Check for a valid email address using regular expression

This method either returns None (if the pattern doesn’t match) or re.MatchObject contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. 

Python3




import re
 
# Make a regular expression
# for validating an Email
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
 
# Define a function for
# for validating an Email
def check(email):
 
    # pass the regular expression
    # and the string into the fullmatch() method
    if(re.fullmatch(regex, email)):
        print("Valid Email")
 
    else:
        print("Invalid Email")
 
# Driver Code
if __name__ == '__main__':
 
    # Enter the email
    email = "ankitrai326@gmail.com"
 
    # calling run function
    check(email)
 
    email = "my.ownsite@our-earth.org"
    check(email)
 
    email = "ankitrai326.com"
    check(email)


Output

Valid Email
Valid Email
Invalid Email

Time complexity : O(n), where n is length of string.

Auxiliary Space : O(1)

Method 2: Validate Email Address with Python using re.match

The re.match() searches only from the beginning of the string and returns the match object if found. But if a match of substring is found somewhere in the middle of the string, it returns none. 

Python3




import re
 
# Define a function for
# for validating an Email
def check(s):
    pat = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
    if re.match(pat,s):
        print("Valid Email")
    else:
        print("Invalid Email")
 
# Driver Code
if __name__ == '__main__':
 
    # Enter the email
    email = "ankitrai326@gmail.com"
 
    # calling run function
    check(email)
 
    email = "my.ownsite@our-earth.org"
    check(email)
 
    email = "ankitrai326.com"
    check(email)


Output

Valid Email
Valid Email
Invalid Email

Method 3: Test if the email address is valid or not in Python using email_validator

This library validates that a string is of the form name@example.com. This is the sort of validation you would want for an email-based login form on a website. Gives friendly error messages when validation fails.

Python3




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, exception message is human-readable
        print(str(e))
 
check("my.ownsite@our-earth.org")
 
check("ankitrai326.com")


Output: 

True
The email address is not valid. It must have exactly one @-sign.

Method 4: Validate Emails From a Text File Using Python

in this method, we will use re.search from regex to validate our from a text file, We can filter out many email from a text file.

Python3




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: 

Valid Email
Invalid Email

Method 5: Validate Emails using an Email Verification API

Email verification services tell you whether an email address is valid syntax, but they also tell you if the address is real and can accept emails, which is super useful and goes beyond just basic validation. The services are usually pretty cheap (like $0.004 USD per email checked). For this example we’ll be using Kickbox, but there are many such services available.

Python3




import kickbox
 
def is_email_address_valid(email, api_key):
    # Initialize Kickbox client with your API key.
    client = kickbox.Client(api_key)
    kbx = client.kickbox()
 
    # Send the email for verification.
    response = kbx.verify(email)
 
    # check the response code if you like
    # assert response.code == 200, "kickbox api bad response code"
    # We can exclude emails that are undeliverable
    return response.body['result'] != "undeliverable"


You can also use the results to check if an email address is disposable ( response.body[‘disposable’] ), or from a free provider – like if you wanted to only accept business email addresses ( response.body[‘free’] ).



Last Updated : 19 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads