3939 DOT_ATOM_TEXT = DOT_ATOM_TEXT .decode ("ascii" )
4040 ATEXT_HOSTNAME = ATEXT_HOSTNAME .decode ("ascii" )
4141
42+ DEFAULT_TIMEOUT = 15 # secs
43+
4244class EmailNotValidError (ValueError ):
4345 """Parent class of all exceptions raised by this module."""
4446 pass
@@ -55,7 +57,8 @@ def validate_email(
5557 email ,
5658 allow_smtputf8 = True ,
5759 allow_empty_local = False ,
58- check_deliverability = True ):
60+ check_deliverability = True ,
61+ timeout = DEFAULT_TIMEOUT ):
5962
6063 """Validates an email address, raising an EmailNotValidError if the address is not valid or returning a dict of information
6164 when the address is valid. The email argument can be a str or a bytes instance, but if bytes it must be ASCII-only."""
@@ -88,7 +91,7 @@ def validate_email(
8891 if check_deliverability :
8992 # Validate the email address's deliverability and update the
9093 # return dict with metadata.
91- ret .update (validate_email_deliverability (ret ["domain" ], ret ["domain_i18n" ]))
94+ ret .update (validate_email_deliverability (ret ["domain" ], ret ["domain_i18n" ], timeout ))
9295
9396 # If the email address has an ASCII form, add it.
9497 ret ["email" ] = ret ["local" ] + "@" + ret ["domain_i18n" ]
@@ -233,13 +236,16 @@ def validate_email_domain_part(domain):
233236 "domain_i18n" : domain_i18n ,
234237 }
235238
236- def validate_email_deliverability (domain , domain_i18n ):
239+ def validate_email_deliverability (domain , domain_i18n , timeout = DEFAULT_TIMEOUT ):
237240 # Check that the domain resolves to an MX record. If there is no MX record,
238241 # try an A or AAAA record which is a deprecated fallback for deliverability.
239242
240243 try :
241244 resolver = dns .resolver .get_default_resolver ()
242245
246+ if timeout :
247+ resolver .lifetime = timeout
248+
243249 try :
244250 # Try resolving for MX records and get them in sorted priority order.
245251 response = dns .resolver .query (domain , "MX" )
@@ -260,7 +266,7 @@ def validate_email_deliverability(domain, domain_i18n):
260266 mtas = [(0 , str (r )) for r in response ]
261267 mx_fallback = "AAAA"
262268 except (dns .resolver .NoNameservers , dns .resolver .NXDOMAIN , dns .resolver .NoAnswer ):
263-
269+
264270 # If there was no MX, A, or AAAA record, then mail to
265271 # this domain is not deliverable.
266272 raise EmailUndeliverableError ("The domain name %s does not exist." % domain_i18n )
0 commit comments