CoolFace
Apppublic

bjarrell333/FK12_Email_Verification

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
utils.py63 linesDownload Raw Back to root
1from validate_email import validate_email2import dns.resolver3import smtplib4from email.utils import parseaddr5import socket6 7def validate_email_address(email: str) -> tuple[bool, str]:8    """9    Validates an email address by checking format and attempting SMTP verification10    Returns a tuple of (is_valid, message)11    """12    try:13        # Basic format check14        if not email or '@' not in email:15            return False, "Invalid email format"16 17        _, domain = email.split('@')18 19        # Check domain length20        if len(domain) > 255:21            return False, "Domain name is too long"22 23        # Verify domain has MX record24        try:25            mx_records = dns.resolver.resolve(domain, 'MX')26            if not mx_records:27                return False, "Domain doesn't have a valid mail server"28 29            # Get the MX server with highest priority30            mx_record = sorted(mx_records, key=lambda x: x.preference)[0]31            mx_domain = str(mx_record.exchange).rstrip('.')32 33            # Attempt SMTP verification34            is_valid = validate_email(35                email_address=email,36                check_format=True,37                check_blacklist=True,38                check_dns=True,39                dns_timeout=10,40                check_smtp=True,41                smtp_timeout=10,42                smtp_helo_host=socket.gethostname(),43                smtp_from_address='verify@example.com',44                smtp_debug=False45            )46 47            if not is_valid:48                return False, "Email address does not exist or cannot receive emails"49 50            return True, "Email address is valid and deliverable!"51 52        except dns.resolver.NXDOMAIN:53            return False, "Domain does not exist"54        except dns.resolver.NoAnswer:55            return False, "Domain does not have mail servers configured"56        except socket.timeout:57            return False, "Connection timed out while verifying email"58        except smtplib.SMTPException as e:59            return False, f"SMTP error: {str(e)}"60 61    except Exception as e:62        return False, f"Validation error: {str(e)}"63