Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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