Skip to content

Instantly share code, notes, and snippets.

@arouene
Created September 27, 2018 15:25
Show Gist options
  • Save arouene/de927d714ec97007d72a1c9652502b22 to your computer and use it in GitHub Desktop.
Save arouene/de927d714ec97007d72a1c9652502b22 to your computer and use it in GitHub Desktop.
Test if an email exists by trying to send an email (but not doing it)
#!/bin/env python
# Test email address
# return code :
# 0 -> OK
# 1 -> Not Valid
# 2 -> Could not connect to mail server
from sys import argv, exit
import dns.resolver
import smtplib
if __name__ == '__main__':
email = argv[1]
user, domain = email.split("@")
try:
ans = dns.resolver.query(domain, "MX")
except dns.resolver.NoAnswer:
print("Domain doesn't have MX records")
exit(1)
except dns.resolver.NXDOMAIN:
print("Domain doesn't exist")
exit(1)
# Sort email servers by preferences
sorted_mail_servers = sorted(ans, key=lambda x: x.preference)
for mail_server in sorted_mail_servers:
server_name = mail_server.exchange.to_text()[:-1] # remove last dot
try:
print("Try to connect to {}".format(server_name))
m = smtplib.SMTP(server_name, 25)
except:
print("Error at connecting server {}".format(server_name))
continue
print("Connected")
status, resp = m.ehlo("example.org")
if status != 250:
print("EHLO refused: {}".format(resp))
exit(1)
print("Sent EHLO")
if "STARTTLS" in resp:
m.starttls()
print("Initiated STARTTLS")
m.ehlo("example.org")
status, resp = m.mail("[email protected]")
if status != 250:
print("Error at MAIL FROM: {}".format(resp))
exit(1)
print("Sent MAIL FROM")
status, resp = m.rcpt(email)
if status != 250:
print("Error at RCPT TO: {}".format(resp))
exit(1)
print("Sent RCPT TO")
exit(0)
print("Could not connect to a server")
exit(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment