Ertdes
Ertdes

Reputation: 189

How to Verify an Email Address in Python Using smtplib

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.

Upvotes: 15

Views: 36010

Answers (4)

HADHIQ KH
HADHIQ KH

Reputation: 1

def is_valid_email(email):

# Validate email format

email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

if not re.match(email_regex, email):
    return False
# Extract domain from email address

domain = email.split('@')[1]

# Perform DNS MX record lookup
try:
    mx_records = dns.resolver.resolve(domain, 'MX')
    mx_record = str(mx_records[0].exchange)
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, dns.exception.Timeout, socket.gaierror):
    return False

# Check if the email is deliverable by connecting to the SMTP server
try:
    server = smtplib.SMTP(mx_record)
    server.helo()
    server.mail('[email protected]')
    code, _ = server.rcpt(email)
    server.quit()
    return code == 250
except (
        smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected, smtplib.SMTPRecipientsRefused,
        smtplib.SMTPException):
    return False

Upvotes: -1

Stephen
Stephen

Reputation: 4296

you need to specify the smtp host (server) in the SMTP construct. This depends on the email domain. eg for a gmail address you would need something like gmail-smtp-in.l.google.com.

The server.verify which is a SMTP VRFY probably isnt what you want though. Most servers disable it.

You might want to look at a service like Real Email which has guide for python. How to Validate Email Address in python.

Upvotes: 0

MrPlow254
MrPlow254

Reputation: 73

The server name isn't defined properly along with the port. Depending on how you have your SMTP server you might need to use the login function.

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

Upvotes: 0

verybadatthis
verybadatthis

Reputation: 1458

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')

Upvotes: 17

Related Questions