Created
May 9, 2017 15:13
-
-
Save otherjoel/1e37bae6f4227fe53b619a370478d237 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load functions for validating email addresses | |
from email.utils import parseaddr | |
from dns.resolver import query | |
from dns.exception import DNSException | |
def check_address(addr): | |
addr_parsed = parseaddr(addr)[1] | |
# An empty string at this point means the address was wildly invalid | |
if addr_parsed == '': | |
return False | |
# The parser accepts anything that is considered technically valid | |
# according to RFC 822, so it still might not be addressable | |
if not '@' in addr_parsed: | |
return False | |
addr_domain = addr_parsed.rsplit('@', 1)[-1] | |
if not '.' in addr_domain: | |
return False | |
# As a final check, look up the MX record for the domain. | |
# If you're on a corporate LAN, make sure you test this with | |
# internal email addresses! Sometimes internal DNS servers | |
# don't have the company's own MX records set up properly. | |
try: | |
dns_check = bool(query(addr_domain, 'MX')) | |
return dns_check | |
except DNSException as exc: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment