I try to verify email and I have some difficulties:
Often I get some errors, for example
dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: siemens.ru. IN MX
What does it mean? I can't check email or another? Or I should try again?
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
Is any way to solve that problem? It appears very often.
dns.resolver.NXDOMAIN: None of DNS query names exist: aruanaestetik.com., aruanaestetik.com.
If I get this error, I should skip email with this domain, right?
Also when I try get mxrecords, sometimes the number of them more than one. Should I use every of it to check email or I can use a random one?
I use next code to do that:
resolver = dns.resolver.Resolver()
resolver.timeout = 60
resolver.lifetime = 60
mx_records = resolver.query(dom, 'MX')
mxRecord = str(mx_records[0].exchange)
host = socket.gethostname()
server = smtplib.SMTP()
server.set_debuglevel(0)
server.connect(mxRecord)
server.helo(host)
server.mail('me@domain.com')
code, message = server.rcpt(str(addressToVerify))
server.quit()
Also I only specify my mail in the server.mail()
, but I try to login there and after that checking email, but don't get any result so I log out. Why does it happen?
There will be no code in my answer, I'd like to describe the process and focus on error handling.
An email address is of the form user@domain.com
To check the domain part, you have to obtain the MX records from DNS. If (and only if) there are no MX's, an A record should be used instead. I would consider such case as a misconfigured mail system, though.
When doing DNS lookup, two groups of error may occur: transient ones (e.g. a timeout) and persistent ones (e.g. NXDOMAIN). In the case of transient errors, the lookup should be repeated later.
There are usually multiple MX records. They have a numeric priority. Smaller number = higher priority. Mail always travels from higher MX number to lower MX number.
In order to check the user part of an address you have to contact the server with the highest priority. All others are backup servers and it is quite common that they have no access to the user database. They simply accept all mail for the own domain.
There is a small chance that your sender address will be rejected for whatever reason. Use an empty address <>
reserved for error messages.
Again, two groups of error exist when communicating with a SMTP server. Fortunately, the SMTP responses have a 3-digit code. The first digit is 2 for success, 4 for transient errors (to be retried later) and 5 for permanent failures.
And a final note: Do a SMTP RSET before QUIT if you are not going to actually send an email.