Open In App

Check if email address valid or not in Python

Last Updated : 30 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 the @ symbol, a “personal_info” and a domain, that is personal_info@domain.

Example: Email Address Validator using re.match()

import re

# Click on Edit and place your email ID to validate
email = "my.ownsite@our-earth.org"
valid = re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email)

print("Valid email address." if valid else "Invalid email address.")

Output
Valid email address.

Check for a valid email address using RegEx

This regex fullmatch 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.

import re

regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'

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)

Validate Emails From a Text File

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.

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

Email Address Validator in Python using email_validator

This email_validator 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.

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.

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(https://kickbox.com/email-verification-api/), but there are many such services available(https://emailverifiers.com/#/).

# Full docs on GitHub - https://github.com/kickboxio/kickbox-python
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’] ).




Next Article

Similar Reads

three90RightbarBannerImg