Blog / Tutorial

Email Regex Python: Validate Emails in Python Using Regex

Fuego Team /

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: Know Who Just Signed Up

A regex only validates format. It can’t tell you that an address belongs to a disposable email service, that the domain has no DNS MX records, or that the signup came from an enterprise worth routing to sales. That’s what Fuego’s lead enrichment API is for. One call, fast enough to run inside your signup flow, returns:

  • Segment: the organization behind the address and its category (enterprise, smb, education, government, nonprofit or individual), plus its name, industry, employee count and country
  • Block abuse: disposable, role and free flags, a DNS-only has_mx check, and a simple risk level
  • Fix typos: a did_you_mean suggestion for mistakes like gmail.cmo
import os
import requests

def enrich_email(email):
    response = requests.get(
        "https://app.gofuego.io/api/v1/enrich",
        params={"email": email, "token": os.environ["FUEGO_KEY"]},
    )
    return response.json()

lead = enrich_email("[email protected]")
print(lead["category"])  # enterprise
print(lead["risk"])      # low

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 go beyond format checks and understand who’s actually signing up, pair regex with an enrichment API. Start a free trial to try it out.

Segment your next signup in under 200ms

Start a free trial today. No survey, no scraped data, no lost signups.