"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Robustly Validate Email Addresses in C#?

How Can I Robustly Validate Email Addresses in C#?

Published on 2025-01-29
Browse:577

How Can I Robustly Validate Email Addresses in C#?
Email address verification in

C#: In -depth analysis

]

When processing an email address, verifying its effectiveness is crucial to ensure that the communication is smooth. This code fragment provides a powerful email address verification solution:

BOOL Isvalidemail (String Email) {{ var trimmedemail = email.trim (); if (Trimmedemail.endswith (".") {{ Return false; @TK-421 Suggestion } try { var addr = new system.net.mail.mailddress (email); Return addr.address == trimmedemail; } catch { Return false; } }
bool IsValidEmail(string email)
{
    var trimmedEmail = email.Trim();

    if (trimmedEmail.EndsWith(".")) {
        return false; // @TK-421 建议
    }
    try {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == trimmedEmail;
    }
    catch {
        return false;
    }
}

Other considerations

error alarm:

This method aims to provide accurate verification without inconsistency (the invalid address is recognized as a valid address).
  • Effectiveness and accessibility: The effectiveness of the email address is different from its accessibility. Although the verification ensures that the string format meets the email standard, it cannot guarantee successful delivery.
  • Domain name inspection: can implement a integrity check to enhance the user experience. Check the known top domain names, MX records and spelling errors to provide additional verification.
  • abnormal processing This code uses abnormal processing to simplify business logic. If any error occurs during the initialization of MAILADDRESS, it will logically convert to an invalid email address without complex conditions.
More resources

System.net.mail.Mailaddress document

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3