@@ -55,7 +55,8 @@ def validate_email(
55
55
email ,
56
56
allow_smtputf8 = True ,
57
57
allow_empty_local = False ,
58
- check_deliverability = True ):
58
+ check_deliverability = True ,
59
+ timeout = 0 ):
59
60
60
61
"""Validates an email address, raising an EmailNotValidError if the address is not valid or returning a dict of information
61
62
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 +89,7 @@ def validate_email(
88
89
if check_deliverability :
89
90
# Validate the email address's deliverability and update the
90
91
# return dict with metadata.
91
- ret .update (validate_email_deliverability (ret ["domain" ], ret ["domain_i18n" ]))
92
+ ret .update (validate_email_deliverability (ret ["domain" ], ret ["domain_i18n" ], timeout ))
92
93
93
94
# If the email address has an ASCII form, add it.
94
95
ret ["email" ] = ret ["local" ] + "@" + ret ["domain_i18n" ]
@@ -233,13 +234,16 @@ def validate_email_domain_part(domain):
233
234
"domain_i18n" : domain_i18n ,
234
235
}
235
236
236
- def validate_email_deliverability (domain , domain_i18n ):
237
+ def validate_email_deliverability (domain , domain_i18n , timeout = 0 ):
237
238
# Check that the domain resolves to an MX record. If there is no MX record,
238
239
# try an A or AAAA record which is a deprecated fallback for deliverability.
239
240
240
241
try :
241
242
resolver = dns .resolver .get_default_resolver ()
242
243
244
+ if timeout :
245
+ resolver .lifetime = timeout
246
+
243
247
try :
244
248
# Try resolving for MX records and get them in sorted priority order.
245
249
response = dns .resolver .query (domain , "MX" )
@@ -260,7 +264,7 @@ def validate_email_deliverability(domain, domain_i18n):
260
264
mtas = [(0 , str (r )) for r in response ]
261
265
mx_fallback = "AAAA"
262
266
except (dns .resolver .NoNameservers , dns .resolver .NXDOMAIN , dns .resolver .NoAnswer ):
263
-
267
+
264
268
# If there was no MX, A, or AAAA record, then mail to
265
269
# this domain is not deliverable.
266
270
raise EmailUndeliverableError ("The domain name %s does not exist." % domain_i18n )
0 commit comments