Skip to content

Commit

Permalink
Merge pull request syrusakbary#18 from cdevienne/master
Browse files Browse the repository at this point in the history
Sanitize check_mx
  • Loading branch information
syrusakbary committed Apr 8, 2014
2 parents b7c5861 + 5599863 commit b41168e
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions validate_email.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
try:
import DNS
ServerError = DNS.ServerError
DNS.DiscoverNameServers()
except ImportError:
DNS = None

Expand Down Expand Up @@ -86,11 +87,18 @@ class ServerError(Exception):
VALID_ADDRESS_REGEXP = '^' + ADDR_SPEC + '$'

MX_DNS_CACHE = {}
MX_CHECK_CACHE = {}


def get_mx_ip(hostname):
if hostname not in MX_DNS_CACHE:
MX_DNS_CACHE[hostname] = DNS.mxlookup(hostname)
try:
MX_DNS_CACHE[hostname] = DNS.mxlookup(hostname)
except ServerError, e:
if e.rcode == 3: # NXDOMAIN (Non-Existent Domain)
MX_DNS_CACHE[hostname] = None
else:
raise

return MX_DNS_CACHE[hostname]

Expand All @@ -116,15 +124,22 @@ def validate_email(email, check_mx=False, verify=False, debug=False, smtp_timeou
if not DNS:
raise Exception('For check the mx records or check if the email exists you must '
'have installed pyDNS python package')
DNS.DiscoverNameServers()
hostname = email[email.find('@') + 1:]
mx_hosts = get_mx_ip(hostname)
if mx_hosts is None:
return False
for mx in mx_hosts:
try:
if not verify and mx[1] in MX_CHECK_CACHE:
return MX_CHECK_CACHE[mx[1]]
smtp = smtplib.SMTP(timeout=smtp_timeout)
smtp.connect(mx[1])
MX_CHECK_CACHE[mx[1]] = True
if not verify:
smtp.quit()
try:
smtp.quit()
except smtplib.SMTPServerDisconnected:
pass
return True
status, _ = smtp.helo()
if status != 250:
Expand Down

0 comments on commit b41168e

Please sign in to comment.