Last active
July 4, 2017 14:10
-
-
Save tspecht/34513785c173ed05d9f89ec81a89f43d to your computer and use it in GitHub Desktop.
Email validation
This file contains hidden or 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
@app.route('/validate', methods=['GET']) | |
def validate(): | |
email = request.args.get('email', '') | |
# Do some basic regex validation first | |
match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', email) | |
if match == None: | |
abort(400) | |
# Extract the host | |
host = email.split('@')[1] | |
# Get the MX record so we can get the SMTP connection afterwards | |
try: | |
records = dns.resolver.query(host, 'MX') | |
mx_record = str(records[0].exchange) | |
except dns.exception.DNSException: | |
# DNS record couldn't be found! | |
abort(400) | |
# SMTP Conversation | |
server = smtplib.SMTP() | |
server.connect(mx_record) | |
server.helo(host) | |
server.mail(email) | |
code, message = server.rcpt(str(email)) | |
server.quit() | |
# Assume 250 as Success | |
if code != 250: | |
abort(400) | |
return "", 200 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment