How to Verify an Email Address in Python Using smtplib

Ertdes picture Ertdes · Mar 6, 2014 · Viewed 22.9k times · Source

I have been trying to verify an email address entered by the user in my program. The code I currently have is:

server = smtplib.SMTP()
server.connect()
server.set_debuglevel(True)
try:
    server.verify(email)
except Exception:
    return False
finally:
    server.quit()

However when I run it I get:

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

So what I am asking is how do i verify an email address using the smtp module? I want to check whether the email address actually exists.

Answer

verybadatthis picture verybadatthis · Jan 29, 2016

Here's a simple way to verify emails. This is minimally modified code from this link. The first part will check if the email address is well-formed, the second part will ping the SMTP server with that address and see if it gets a success code (250) back or not. That being said, this isn't failsafe -- depending how this is set up sometimes every email will be returned as valid. So you should still send a verification email.

email_address = '[email protected]'

#Step 1: Check email
#Check using Regex that an email meets minimum requirements, throw an error if not
addressToVerify = email_address
match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', addressToVerify)

if match == None:
    print('Bad Syntax in ' + addressToVerify)
    raise ValueError('Bad Syntax')

#Step 2: Getting MX record
#Pull domain name from email address
domain_name = email_address.split('@')[1]

#get the MX record for the domain
records = dns.resolver.query(domain_name, 'MX')
mxRecord = records[0].exchange
mxRecord = str(mxRecord)

#Step 3: ping email server
#check if the email address exists

# Get local server hostname
host = socket.gethostname()

# SMTP lib setup (use debug level for full output)
server = smtplib.SMTP()
server.set_debuglevel(0)

# SMTP Conversation
server.connect(mxRecord)
server.helo(host)
server.mail('[email protected]')
code, message = server.rcpt(str(addressToVerify))
server.quit()

# Assume 250 as Success
if code == 250:
    print('Y')
else:
    print('N')