defvalidate_email(email,check_mx=False,verify=False,debug=False,smtp_timeout=10):"""Indicate whether the given string is a valid email address according to the 'addr-spec' portion of RFC 2822 (see section 3.4.1). Parts of the spec that are marked obsolete are *not* included in this test, and certain arcane constructions that depend on circular definitions in the spec may not pass, but in general this should correctly identify any email address likely to be in use as of 2011."""ifdebug:logger=logging.getLogger('validate_email')logger.setLevel(logging.DEBUG)else:logger=Nonetry:assertre.match(VALID_ADDRESS_REGEXP,email)isnotNonecheck_mx|=verifyifcheck_mx:ifnotDNS:raiseException('For check the mx records or check if the email exists you must ''have installed pyDNS python package')hostname=email[email.find('@')+1:]mx_hosts=get_mx_ip(hostname)ifmx_hostsisNone:returnFalseformxinmx_hosts:try:ifnotverifyandmx[1]inMX_CHECK_CACHE:returnMX_CHECK_CACHE[mx[1]]smtp=smtplib.SMTP(timeout=smtp_timeout)smtp.connect(mx[1])MX_CHECK_CACHE[mx[1]]=Trueifnotverify:try:smtp.quit()exceptsmtplib.SMTPServerDisconnected:passreturnTruestatus,_=smtp.helo()ifstatus!=250:smtp.quit()ifdebug:logger.debug(u'%s answer: %s - %s',mx[1],status,_)continuesmtp.mail('')status,_=smtp.rcpt(email)ifstatus==250:smtp.quit()returnTrueifdebug:logger.debug(u'%s answer: %s - %s',mx[1],status,_)smtp.quit()exceptsmtplib.SMTPServerDisconnected:# Server not permits verify userifdebug:logger.debug(u'%s disconected.',mx[1])exceptsmtplib.SMTPConnectError:ifdebug:logger.debug(u'Unable to connect to %s.',mx[1])returnNoneexceptAssertionError:returnFalseexcept(ServerError,socket.error)ase:ifdebug:logger.debug('ServerError or socket.error exception raised (%s).',e)returnNonereturnTrue