DEV Community

Brad
Brad

Posted on

Python Email Validator: Check 10,000 Emails in Under a Minute

Python Email Validator: Check 10,000 Emails in Under a Minute

Stop sending emails to dead addresses. This Python script validates email lists in bulk.

Install

pip install dnspython
Enter fullscreen mode Exit fullscreen mode

The Script

import re
import dns.resolver
from concurrent.futures import ThreadPoolExecutor

def validate_format(email):
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))

def check_mx(domain):
    try:
        dns.resolver.resolve(domain, 'MX')
        return True
    except:
        return False

def validate(email):
    if not validate_format(email): return False, 'bad_format'
    domain = email.split('@')[1]
    if not check_mx(domain): return False, 'no_mx'
    return True, 'valid'

def batch_validate(emails, workers=50):
    with ThreadPoolExecutor(max_workers=workers) as ex:
        return list(ex.map(validate, emails))

emails = ['user@gmail.com', 'bad@fake12345.com', 'test@python.org']
results = batch_validate(emails)
for email, (valid, reason) in zip(emails, results):
    print(f'{email}: {valid} ({reason})')
Enter fullscreen mode Exit fullscreen mode

Scale to 10,000 Emails

With 100 workers, 10,000 emails takes under 60 seconds.

Want 50 More Scripts?

The Python Business Automation Toolkit includes this + 49 more scripts.
$9 one-time download.

What email automation challenge are you solving?

Top comments (0)