Skip to content

Instantly share code, notes, and snippets.

@tspecht
Last active July 4, 2017 14:10
Show Gist options
  • Save tspecht/34513785c173ed05d9f89ec81a89f43d to your computer and use it in GitHub Desktop.
Save tspecht/34513785c173ed05d9f89ec81a89f43d to your computer and use it in GitHub Desktop.
Email validation
@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