Python SMTP Checks for Cleaner Email Lists
SMTP verification uses a mail server’s response to assess whether an address appears deliverable. In Python, this usually means resolving the recipient domain’s MX records, opening an SMTP connection, and issuing MAIL FROM and RCPT TO commands without sending a message. The result is a useful signal, not a guarantee that a person will receive or read an email.
For Australian marketers, accuracy matters across mixed audiences: a Sydney retailer may use Microsoft 365, a Brisbane trades business may host mail with an Australian provider, and a .au domain may enforce stricter filtering than a free mailbox. A careful workflow reduces bounces while respecting the Spam Act 2003, consent requirements, and the policies of recipient networks.
| Method | What it checks | Advantages | Main limitation |
|---|---|---|---|
| Syntax validation | Address format | Very fast and inexpensive | Cannot prove the mailbox exists |
| Domain and MX lookup | Whether the domain accepts mail | Avoids pointless SMTP connections | Says nothing about a specific address |
| SMTP handshake | Server response for a recipient | Stronger deliverability signal | Servers may hide or distort results |
| Confirmation email | Real-world inbox access | Most reliable permission signal | Sends a message and needs user action |
What an SMTP handshake actually does
An SMTP session begins when the client connects to the recipient domain’s mail exchanger. The client identifies itself with EHLO, optionally upgrades the connection with STARTTLS, and presents a sender during MAIL FROM. The RCPT TO command asks whether the server will accept mail for the target address.
A successful RCPT TO response commonly uses a 250 or 251 status. A permanent 550 or 553 response may indicate an invalid mailbox, while a 421, 450, or 451 response usually means the server is temporarily unavailable or applying a policy restriction. Many providers deliberately return ambiguous responses to prevent address harvesting, so “accepted” should be treated as “probably deliverable”.
The process should stop after the recipient command. Do not issue DATA, transmit marketing content, or attempt to evade connection controls. This distinction keeps the check focused on list hygiene rather than turning it into unsolicited mail automation.
Preparing a responsible Python workflow
Use a syntax checker before contacting any server. Reject malformed addresses, internationalised domains that your tooling cannot handle, disposable domains if they are unsuitable for your campaign, and obvious role addresses such as admin@ or sales@ when your business rules require individual contacts.
For MX lookups, the dnspython package is practical:
python -m pip install dnspython
A minimal lookup can be written as:
import dns.resolver
def mail_hosts(domain):
try:
answers = dns.resolver.resolve(domain, "MX", lifetime=5)
return [str(record.exchange).rstrip(".")
for record in sorted(answers, key=lambda item: item.preference)]
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer,
dns.resolver.LifetimeTimeout):
return []
Some domains use a null MX record to state that they do not receive email. Check for that condition before opening an SMTP session. Cache DNS results so a large list does not repeatedly query the same domain.
Implementing the SMTP probe
Python’s standard smtplib supports the handshake without requiring a full email-sending library. The example below uses a controlled sender address on a domain you operate, applies a timeout, and returns a cautious classification.
import smtplib
def probe(recipient, mx_host, sender="verifier@example.com"):
try:
with smtplib.SMTP(mx_host, 25, timeout=10) as smtp:
smtp.ehlo()
if smtp.has_extn("starttls"):
smtp.starttls()
smtp.ehlo()
smtp.mail(sender)
code, message = smtp.rcpt(recipient)
if 200 <= code < 300:
return "accepted", code, message.decode(errors="replace")
if 400 <= code < 500:
return "temporary", code, message.decode(errors="replace")
return "rejected", code, message.decode(errors="replace")
except (OSError, smtplib.SMTPException) as error:
return "unknown", None, str(error)
Port 25 is often blocked by cloud providers and residential networks. A production system should distinguish connection failures from mailbox rejections, record the MX host and response code, and avoid treating every timeout as an invalid address. Never use VRFY as a shortcut; it is commonly disabled and can create unnecessary security alerts.
Handling modern mail-server behaviour
Large providers frequently accept every recipient during the SMTP conversation and reject bad addresses later, or they route all unknown addresses to a catch-all mailbox. An SMTP handshake therefore cannot guarantee deliverability. It also cannot identify whether an inbox is abandoned, over quota, or controlled by a real person.
Use a result model with states such as valid_signal, invalid_signal, temporary_failure, catch_all, and unknown. Recheck temporary failures later with exponential backoff rather than repeatedly hammering the same server. A second result from a different time can improve confidence, but it still should not override a confirmed unsubscribe or complaint.
Some systems require reverse DNS, valid TLS behaviour, and a sensible EHLO hostname before they respond normally. A verifier running in a Melbourne data centre may receive different treatment from one hosted in Sydney or overseas. Use a stable, properly configured host and identify it honestly.
Scaling checks without damaging reputation
Batch processing should use a queue, a small worker count, per-domain throttles, and a global rate limit. Grouping addresses by domain reduces repeated DNS work, while jitter between requests avoids a predictable burst. Store only the fields needed for list hygiene, protect logs, and set a retention period for SMTP responses.
Australian sending practices require particular care. The ACMA Spam Act 2003 generally requires consent, sender identification, and a functional unsubscribe facility for commercial electronic messages. Verifying an address does not create consent. If a list was collected from public pages around Perth, Adelaide, or Canberra, publication does not automatically authorise promotional email.
For local campaigns, schedule any eventual mail according to the audience’s time zone rather than assuming Sydney time covers all recipients. Consider Australian Eastern, Central, and Western time zones, as well as daylight saving differences between states. Good operational timing and restrained connection rates help protect both your domain and the recipient’s infrastructure.
Measuring quality beyond SMTP results
Track hard-bounce rates after real campaigns and compare them with handshake classifications. If many addresses marked accepted later bounce, the target provider may be using catch-all behaviour or your probe may be too aggressive. Treat confirmation links, recent engagement, and consent records as stronger business signals than an SMTP response alone.
A practical pipeline can run local syntax checks, resolve MX records, perform a limited handshake, remove confirmed failures, and place uncertain addresses into a review queue. Addresses that are accepted but have no consent should remain excluded from marketing until permission is established. This is especially important for Australian customer data collected through lead forms, events, trade shows, and loyalty programmes.
Safer alternatives for list validation
A double opt-in email remains the clearest way to confirm that a person controls an address and wants communications. It creates an auditable permission trail and can be paired with a short confirmation window, preference centre, and easy unsubscribe process. For transactional systems, use address verification at form submission instead of repeatedly probing an old database.
SMTP checks are most useful as one layer in a broader data-quality system. Combine them with domain reputation checks, suppression lists, duplicate detection, consent timestamps, and bounce feedback from your authorised email service. Used conservatively, Python can automate useful mailbox-risk screening without sending content, evading provider controls, or turning public contact data into unsolicited campaigns.
BlackHatProTools