Created
September 15, 2014 01:32
-
-
Save bremac/d1c880e9a3ad3989eda2 to your computer and use it in GitHub Desktop.
Check an email address in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import smtplib | |
import dns.resolver | |
def get_mx_records(domain): | |
try: | |
records = dns.resolver.query(domain, "MX") | |
preferred = sorted(records, key=lambda r: r.preference) | |
return [r.exchange.to_text(omit_final_dot=True) for r in preferred] | |
except dns.resolver.NXDOMAIN: | |
return [] | |
def get_domain_part(email_address): | |
return receiver[receiver.index("@") + 1:] | |
def send_smtp_command(s, command, **kwargs): | |
status, response = s.docmd(command) | |
expected = kwargs.get("expected") | |
if expected and status != expected: | |
msg = "Expected status {0}, received {1} {2}".format( | |
expected, status, response) | |
raise AssertionError(msg) | |
return status | |
def ping_exchange(exchange, receiver, sender): | |
s = smtplib.SMTP(exchange, 25) | |
send_smtp_command(s, "HELO", expected=250) | |
send_smtp_command(s, "MAIL FROM: <{}>".format(sender), expected=250) | |
status = send_smtp_command(s, "RCPT TO: <{}>".format(receiver)) | |
send_smtp_command(s, "QUIT") | |
return status == 250 | |
def ping(receiver, sender): | |
if "@" not in receiver: | |
return False | |
domain = get_domain_part(receiver) | |
exchanges = get_mx_records(domain) | |
if exchanges: | |
return ping_exchange(exchanges[0], receiver, sender) | |
else: | |
return False | |
if __name__ == "__main__": | |
from sys import argv | |
receiver, sender = argv[1], argv[2] | |
success = ping(receiver, sender) | |
if success: | |
print("Successfully contacted %s from %s" % (receiver, sender)) | |
else: | |
print("Could not contact %s from %s" % (receiver, sender)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dnspython==1.12.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment