From a6a10744aafec3411816022cb7799e72b344429a Mon Sep 17 00:00:00 2001 From: Andrea Crotti Date: Tue, 7 Jan 2014 11:51:50 +0000 Subject: [PATCH] cache the mx from the cache since it's very unlikely to change and we can spare many DNS requests --- validate_email.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/validate_email.py b/validate_email.py index ebff013..171ccd0 100644 --- a/validate_email.py +++ b/validate_email.py @@ -85,6 +85,15 @@ ADDR_SPEC = LOCAL_PART + r'@' + DOMAIN # see 3.4.1 # A valid address will match exactly the 3.4.1 addr-spec. VALID_ADDRESS_REGEXP = '^' + ADDR_SPEC + '$' +MX_DNS_CACHE = {} + + +def get_mx_ip(hostname): + if hostname not in MX_DNS_CACHE: + MX_DNS_CACHE[hostname] = DNS.mxlookup(hostname) + + return MX_DNS_CACHE[hostname] + def validate_email(email, check_mx=False, verify=False, debug=False): """Indicate whether the given string is a valid email address @@ -109,7 +118,7 @@ def validate_email(email, check_mx=False, verify=False, debug=False): 'have installed pyDNS python package') DNS.DiscoverNameServers() hostname = email[email.find('@') + 1:] - mx_hosts = DNS.mxlookup(hostname) + mx_hosts = get_mx_ip(hostname) for mx in mx_hosts: try: smtp = smtplib.SMTP()