Check that email address is valid for System.Net.Mail.MailAddress

Deadly 提交于 2019-11-29 02:51:37

Unfortunately, there is no MailAddress.TryParse method.

Your code is the ideal way to validate email addresses in .Net.

If you need to make sure a given email address is valid according to the IETF standards - which the MailAddress class seems to follow only partially, at the time of this writing - I suggest you to take a look at EmailVerify.NET, a .NET component you can easily integrate in your solutions. It does not depend on regular expressions to perform its job but it relies on an internal finite state machine, so it is very very fast.

Disclaimer: I am the lead developer of this component.

Not really an answer to this question per se, but in case anyone needs it, I wrote a C# function for validating email addresses using this method.

FixEmailAddress("walter@xyz.com")

returns "walter@xyz.com"

FixEmailAddress("wa@lter@xyz.com,tom@xyz.com,asdfdsf,vsav-sdfsd@xyz.xyz")

returns "tom@xyz.com,vsav-sdfsd@xyz.xyz"

I process lists of email addresses this way because a comma separated list of emails is a valid parameter for MailAddressCollection.Add()

/// <summary>
/// Given a single email address, return the email address if it is valid, or empty string if invalid.
/// or given a comma delimited list of email addresses, return the a comma list of valid email addresses from the original list.
/// </summary>
/// <param name="emailAddess"></param>
/// <returns>Validated email address(es)</returns>  
public static string FixEmailAddress(string emailAddress)
{

   string result = "";

    emailAddress = emailAddress.Replace(";",",");
   if (emailAddress.Contains(","))
   {
       List<string> results = new List<string>();
       string[] emailAddresses = emailAddress.Split(new char[] { ',' });
       foreach (string e in emailAddresses)
       {
           string temp = FixEmailAddress(e);
           if (temp != "")
           {
               results.Add(temp);
           }
       }
       result = string.Join(",", results);
   }
   else
   {

       try
       {
           System.Net.Mail.MailAddress email = new System.Net.Mail.MailAddress(emailAddress);
           result = email.Address;
       }
       catch (Exception)
       {
           result = "";
       }

   }

   return result;

}

Some characters are valid in some service providers but the same is not in others! The SmtpClient don't know anything about the service providers. So it has to filter as least as possible. The Wikipedia is welly mentioned about the standers.

Validation of MailAddress is mentioned on the MSDN. Hence I think you can check for those validations before initializing the MailAddress.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!