Blog / Tutorial
Email Regex Python: Validate Emails in Python Using Regex
Email validation is a crucial step for both marketers and software engineers to ensure the integrity of user data. One effective tool for this purpose is using Python with regular expressions (regex). This blog post will guide you through a practical approach to validate email address formats with regex in Python. Remember that regex checks format only. It can’t tell you who is behind an address or whether it’s a throwaway.
Why Validate Emails?
Validating emails is essential to:
- Catch malformed input early.
- Prevent fraudulent signups.
- Maintain data quality in databases.
- Give users instant feedback on typos.
Setting Up Your Python Environment
First, make sure you have Python installed on your system. You can check this by running:
python --version
If Python isn’t installed, you can download it from the Python official site.
Basic Regex for Email Validation
A basic regex pattern to match most email formats looks like this:
import re
email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$'
Here’s a breakdown of this regex pattern:
^asserts the position at the start of the string.[a-zA-Z0-9_.+-]+matches one or more upper/lowercase letters, digits, underscores, dots, plus, or minus signs.@matches the at symbol.[a-zA-Z0-9-]+matches the domain part before a dot.\.[a-zA-Z0-9.-]+$matches the dot followed by one or more letters, digits, dots, or hyphens until the end of the string.
Validating Email Addresses
Now, let’s write a function to validate email addresses using the regex pattern above.
import re
def validate_email(email):
email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$'
return re.match(email_regex, email) is not None
# Example usage
emails = ['[email protected]', 'invalid-email@domain', '[email protected]']
for email in emails:
if validate_email(email):
print(f"{email} is valid.")
else:
print(f"{email} is invalid.")
Expected Output
[email protected] is valid.
invalid-email@domain is invalid.
[email protected] is valid.
Practicing with Real-World Emails
To further ensure the effectiveness of your regex, it’s useful to test it with real-world email lists. Be cautious, however, as overly restrictive regex patterns might wrongly invalidate legitimate emails. The regex provided is good enough without being overly fussy about the exact form of the email.
Beyond Regex: Verify the Address
A regex only checks format. It can’t tell you whether the mailbox actually exists, whether the domain accepts every address you throw at it, or whether the address is a disposable throwaway. Fuego’s email verification API answers those questions with a real SMTP check, and includes domain intelligence about the company behind the address at no extra cost:
- Verify: a
resultofdeliverable,undeliverable,riskyorunknown, plus areasonlikeaccepted_emailorinvalid_domain - Flag risky signups:
disposable,role,freeandaccept_allflags - Fix typos: a
did_you_meansuggestion for mistakes likegmial.com - Know the company: a free
domain_insightobject with the organization’s name, industry, employee count and country
import os
import requests
def verify_email(email):
response = requests.get(
"https://app.gofuego.io/api/v1/verify",
params={"email": email, "token": os.environ["FUEGO_KEY"]},
)
return response.json()
check = verify_email("[email protected]")
print(check["result"]) # deliverable
print(check["domain_insight"]["name"]) # Jupiter Mining Corporation
For a full walkthrough, see our guide to integrating the Fuego API with Python.
Conclusion
Email validation using regex in Python is an efficient first line of defense against malformed input. Whether you’re cleaning user entries or guarding a signup form, understanding and implementing practical regex patterns is crucial.
Experiment with the regex example provided, and adapt it to fit your specific requirements. To know an address is real before you rely on it, pair regex with an email verification API. Start a free trial to try it out.