Reputation: 1659
I am creating a python function to check whether a given email ID really exists or not in Python. Here is my code:
def email_validate(email_address):
addressToVerify = email_address
domain_name = addressToVerify.split('@')[1]
try:
records = dns.resolver.query(domain_name, 'MX')
except Exception as e:
print e
a = traceback.format_exc()
print a
return HttpResponse(json.dumps({"success":False,"message":"Email Domain is not valid."}), content_type="application/json")
mxRecord = records[0].exchange
mxRecord = str(mxRecord)
server = smtplib.SMTP()
server.set_debuglevel(0)
# SMTP Conversation
server.connect(mxRecord)
server.helo(host)
server.mail('[email protected]')
try:
code, message = server.rcpt(str(addressToVerify))
server.quit()
except:
a = traceback.format_exc()
if code == 250:
return HttpResponse(json.dumps({"success":True,"message":"Email ID is valid."}), content_type="application/json")
else:
return HttpResponse(json.dumps({"success":False,"message":"Email ID is not valid."}), content_type="application/json")
This code works fine for Gmail accounts, but it gives an error for other email ID's. If I try other Email ID's, this line:
code, message = server.rcpt(str(addressToVerify))
gives an error... Also, how should I check this for other email ID's?
Upvotes: 1
Views: 4579
Reputation: 51
If you only need to check emails in your google domain for G Suite you can use these:
1) First you need to get the right credentials to be able to access data for the scope https://www.googleapis.com/auth/admin.directory.user.readonly -- https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account
2) Second you can use the service object created with these credentials to check if the email exists: https://developers.google.com/admin-sdk/directory/v1/quickstart/python
Upvotes: 0
Reputation:
An RCPT command is never a good idea to check for email validation, most SMTP servers will ban your IP after several attempts or ignore you command to keep their emails safe from spammers. The only way to validate an email existance is to send a validation email.
Upvotes: 6