Skip to content

Instantly share code, notes, and snippets.

@johnnyg
Last active July 30, 2018 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnnyg/2965479 to your computer and use it in GitHub Desktop.
Save johnnyg/2965479 to your computer and use it in GitHub Desktop.
Checks whether or not an email actually exists
#!/usr/bin/env python
# Requires dnspython
from __future__ import print_function
from dns.exception import DNSException
from dns.resolver import query
from smtplib import SMTP, SMTPException
def get_mx_records(domain):
try:
records = query(domain, 'MX')
except DNSException:
records = []
return (r.exchange.to_text(omit_final_dot=True) for r in records)
def check_email_address(hostname, email):
smtp = SMTP(hostname)
code, msg = smtp.helo('localhost')
code, msg = smtp.mail('<testing@testing.com>')
code, msg = smtp.rcpt('<%s>' % email)
return code in (250, 251)
def is_valid_email(email):
domain = email.partition('@')[2]
for hostname in get_mx_records(domain):
try:
is_valid = check_email_address(hostname, email)
except SMTPException:
continue
else:
break
else:
is_valid = False
return is_valid
if __name__ == '__main__':
import sys
for arg in sys.argv[1:]:
print("{} is".format(arg), end='')
if is_valid_email(arg):
print("valid")
else:
print("invalid")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment