import re
import dns.resolver
import socket
def is_valid_email(email):
# Regular expression pattern for email validation
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Validate email format
if not re.match(email_regex, email):
return False
# Split email address to retrieve the domain
domain = email.split('@')[1]
try:
# Perform a DNS query to get MX records of the domain
mx_records = dns.resolver.query(domain, 'MX')
# Open a socket connection to the first MX record to check its validity
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
mx_record = str(mx_records[0].exchange)[:-1]
sock.settimeout(2)
sock.connect((mx_record, 25))
return True # Email address is valid
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
return False # Domain does not exist
except (socket.timeout, ConnectionRefusedError):
return False # No valid MX record
email_to_check = "example@example.com"
if is_valid_email(email_to_check):
print(f"{email_to_check} is a valid email address.")
else:
print(f"{email_to_check} is not a valid email address.")