Check if email address valid or not in Python
Last Updated :
30 Sep, 2024
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()
Python
import re
# Click on Edit and place your email ID to validate
email = "[email protected]"
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.")
OutputValid 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.
Python
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 = "[email protected]"
# calling run function
check(email)
email = "[email protected]"
check(email)
email = "ankitrai326.com"
check(email)
OutputValid 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.
Python
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 [email protected]. 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.
Python
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("[email protected]")
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/#/).
Python
# 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'] ).
Similar Reads
Check if String is Empty or Not - Python We are given a string and our task is to check whether it is empty or not. For example, if the input is "", it should return True (indicating it's empty), and if the input is "hello", it should return False. Let's explore different methods of doing it with example:Using Comparison Operator(==)The si
2 min read
Python | Check whether a string is valid json or not Given a Python String, the task is to check whether the String is a valid JSON object or not. Let's try to understand the problem using different examples in Python. Validate JSON String in PythonThere are various methods to Validate JSON schema in Python here we explain some generally used methods
3 min read
Python program to validate an IP Address Prerequisite: Python Regex Given an IP address as input, write a Python program to check whether the given IP Address is Valid or not. What is an IP (Internet Protocol) Address? Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) a
4 min read
Python Check if Nonetype or Empty In Python, it's common to check whether a variable is of NoneType or if a container, such as a list or string, is empty. Proper handling of such scenarios is crucial for writing robust and error-free code. In this article, we will explore various methods to check if a variable is either of NoneType
3 min read
Python | Check if string is a valid identifier Given a string, write a Python program to check if it is a valid identifier or not. An identifier must begin with either an alphabet or underscore, it can not begin with a digit or any other special character, moreover, digits can come after gfg : valid identifier 123 : invalid identifier _abc12 : v
3 min read