Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@badbye
Last active July 8, 2020 09:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badbye/41aa2025a2e0d048d42c086b9c2cbee2 to your computer and use it in GitHub Desktop.
Save badbye/41aa2025a2e0d048d42c086b9c2cbee2 to your computer and use it in GitHub Desktop.
Check the validation of an email
# encoding: utf8
"""
Created on 2017.06.27
@author: yalei
Reference:
1. http://www.ruanyifeng.com/blog/2017/06/smtp-protocol.html
2. http://blog.online-domain-tools.com/2014/11/14/how-to-verify-email-address/
"""
import sys
import dns.resolver
from smtplib import SMTP
def check_mail(email, timeout=30):
domain = email.split('@')[-1]
try:
mx = dns.resolver.query(domain, 'MX')
server = list(mx)[0].exchange.to_text().rstrip('.')
except dns.resolver.NXDOMAIN as e:
return False, str(e)
try:
smtp = SMTP(server, timeout=timeout)
status_code, msg = smtp.helo(domain)
if status_code != 250:
smtp.quit()
return False, msg
status_code, msg = smtp.docmd('MAIL FROM:<webmaster@python.org>')
if status_code != 250:
smtp.quit()
return False, msg
status_code, msg = smtp.docmd("RCPT TO:<%s>" % email)
if status_code != 250:
smtp.quit()
return False, msg
smtp.quit()
return True, ''
except Exception as e:
return False, str(e)
if __name__ == '__main__':
# test
if len(sys.argv) == 2:
e = sys.argv[1]
print('[%s] is valid: %s' % (e, check_mail(e)[0]))
sys.exit()
normal_emails = ['python-tornado@googlegroups.com',
'webmaster@python.org']
print('Check normal emails:')
for e in normal_emails:
print('[%s] is valid: %s' % (e, check_mail(e)[0]))
error_emails = ['python-tornado@gmail.com',
'12312eqwdsarfAFD@python.org']
print('\nCheck error emails:')
for e in error_emails:
print('[%s] is valid: %s' % (e, check_mail(e)[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment