Best way to parse string of email addresses

后端 未结 13 2644
悲哀的现实
悲哀的现实 2021-02-14 04:10

So i am working with some email header data, and for the to:, from:, cc:, and bcc: fields the email address(es) can be expressed in a number of different ways:

F         


        
13条回答
  •  不思量自难忘°
    2021-02-14 04:59

    The clean and short solution is to use MailAddressCollection:

    var collection = new MailAddressCollection();
    collection.Add(addresses);
    

    This approach parses a list of addresses separated with colon ,, and validates it according to RFC. It throws FormatException in case the addresses are invalid. As suggested in other posts, if you need to deal with invalid addresses, you have to pre-process or parse the value by yourself, otherwise recommending to use what .NET offers without using reflection.

    Sample:

    var collection = new MailAddressCollection();
    collection.Add("Joe Doe , postmaster@example.com");
    
    foreach (var addr in collection)
    {
      // addr.DisplayName, addr.User, addr.Host
    }
    

提交回复
热议问题