Created
October 23, 2012 12:59
-
-
Save elidickinson/3938595 to your computer and use it in GitHub Desktop.
Script to check that a list of email address have valid domains (i.e. they have an MX record)
This file contains 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
# pip install pydns | |
import DNS, smtplib | |
import csv, re | |
in_filename = 'input.csv' | |
skip_to = None | |
# DNS.DiscoverNameServers() | |
DNS.defaults['server'].append('208.67.222.222') | |
DNS.defaults['server'].append('208.67.222.220') | |
DNS.defaults['timeout'] = 5 | |
cached_lookups = {} | |
# import pdb; pdb.set_trace() | |
def has_mx(hostname): | |
if hostname in cached_lookups.keys(): | |
return cached_lookups[hostname] | |
result = False | |
i = 0 | |
while i < 3: | |
i = i+1 | |
DNS.defaults['timeout'] = i+2 | |
try: | |
mx_hosts = DNS.mxlookup(hostname) | |
result = (len(mx_hosts) > 0) | |
except DNS.Base.ServerError as e: | |
if e[1] == 3 or e[1] == 2: | |
result = False | |
else: | |
raise | |
except DNS.Base.TimeoutError: | |
# print "(timeout on %s)" % hostname | |
continue | |
break | |
# except DNS.Base.TimeoutError: | |
# result = True | |
cached_lookups[hostname] = result | |
return result | |
input = file(in_filename,'rU') | |
c = csv.reader(input) | |
if skip_to: | |
for row in c: | |
if row[0] == skip_to: | |
break | |
for row in c: | |
email = row[0] | |
# print email | |
m = re.match(r"^.+?@(.+\..+)$", email) | |
if not m: | |
# print "invalid: %s" % email | |
print "%s,INVALID" % email | |
else: | |
domain = m.group(1) | |
# print "%s - %s: %s" % (email,domain,has_mx(domain)) | |
try: | |
print "%s,%s" % (email, has_mx(domain)) | |
except DNS.Base.TimeoutError: | |
print "%s,TIMEOUT" % email | |
continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/syrusakbary/validate_email looks good as well