Python Validate Email: Check Email Addresses via SMTP

Validating email addresses is a common task for developers, especially when building contact forms, email marketing systems, or lead generation tools. In this tutorial, we will show you how to validate email addresses in Python using MX record lookup and SMTP checks.

Why Validate Emails in Python?

Emails can often contain typos or belong to domains that don’t exist. By validating emails programmatically:

  • You reduce bounce rates in email campaigns.
  • You improve the quality of your mailing list.
  • You prevent errors when sending important notifications.

Python Code Example

Here’s a simplified example of Python code to demonstrate the process:

import dns.resolver
import smtplib

def get_mx_record(domain):
    try:
        mx_records = dns.resolver.resolve(domain, "MX", lifetime=5)
        if mx_records:
            return str(mx_records[0].exchange).strip(".")
    except:
        return None

def smtp_check(email, mx_record):
    try:
        server = smtplib.SMTP(timeout=15)
        server.connect(mx_record)
        server.helo("example.com")
        server.mail("test@example.com")
        code, _ = server.rcpt(email)
        server.quit()
        return code
    except:
        return None

How the Script Works

  1. MX Lookup: Retrieves the domain’s MX record.
  2. SMTP Check: Sends a test command to check if the email exists.

Tips

  • Use a domain correctly configured with reverse DNS (PTR records), DKIM, DMARC, SPF, and valid MX records for the SMTP check.
  • Validating catch-all domains is possible but more complex than shown here.
  • For large volumes of emails, intelligent caching of MX records is recommended.
  • This code requires a server with SMTP ports open (25, 465, or 587). More info: VPS with Open Port 25.

Conclusion

Using Python for email validation is a practical approach for developers, but for large-scale and accurate validation, I recommend using my software, Matchkraft, which offers unlimited email validations with the highest accuracy.

Leave a Reply

Your email address will not be published. Required fields are marked *