Skip to content

Instantly share code, notes, and snippets.

@dwinston
Created January 11, 2018 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwinston/eaa57dc198923ef7bcf0ba30c2e3a39f to your computer and use it in GitHub Desktop.
Save dwinston/eaa57dc198923ef7bcf0ba30c2e3a39f to your computer and use it in GitHub Desktop.
Use dnspython library to validate an email domain via DNS MX, AAAA, and A records. A sanity check that avoids abusing the email server.
import re
import dns.resolver
def dns_check_email_domain(domain):
"""
Query DNS records to verify that email server is possible on domain.
If no DNS records are found, user should confirm email address.
"""
response = {}
# Check for '.' in domain to filter out relative domains
if re.match('^.+\..+$', domain, re.I) is None:
msg = "Not possibly a valid domain: '{}'".format(domain)
response['error'] = msg
return response
record_types = ('MX', 'AAAA', 'A')
for record_type in record_types:
try:
if len(dns.resolver.query(domain, record_type)):
msg = "Found {} record(s) for {}".format(record_type, domain)
response['success'] = msg
return response
except:
continue
msg = "No DNS records of types {} found for {}".format(record_types, domain)
response['warning'] = msg
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment