[Python] dynamically finding SMTP Server using Email Address

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a Python function to find SMTP host and port of an Email address

    import dns.resolver

    def get_smtp_host(email):
    try:
    # Extract the domain from the email address
    domain = email.split('@')[1]

    # Query the MX records for the domain
    mx_records = dns.resolver.resolve(domain, 'MX')

    # Sort the MX records by priority (lower number means higher priority)
    sorted_mx_records = sorted(mx_records, key=lambda x: x.preference)

    # Get the highest priority MX record
    highest_priority_mx = sorted_mx_records[0].exchange.to_text()

    # Return the SMTP host
    return highest_priority_mx
    except Exception as e:
    return f"Error: {e}"

    # Example usage
    email = "abcp@gmail.com"
    smtp_host = get_smtp_host(email)
    print(smtp_host)


    I am getting output of the MX record. Cannot find a way to get SMTP host and port.

    Continue reading...

Compartilhe esta Página