Best way to parse string of email addresses

后端 未结 13 2617
悲哀的现实
悲哀的现实 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 05:11

    There is internal System.Net.Mail.MailAddressParser class which has method ParseMultipleAddresses which does exactly what you want. You can access it directly through reflection or by calling MailMessage.To.Add method, which accepts email list string.

    private static IEnumerable ParseAddress(string addresses)
    {
        var mailAddressParserClass = Type.GetType("System.Net.Mail.MailAddressParser");
        var parseMultipleAddressesMethod = mailAddressParserClass.GetMethod("ParseMultipleAddresses", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
        return (IList)parseMultipleAddressesMethod.Invoke(null, new object[0]);
    }
    
    
        private static IEnumerable ParseAddress(string addresses)
        {
            MailMessage message = new MailMessage();
            message.To.Add(addresses);
            return new List(message.To); //new List, because we don't want to hold reference on Disposable object
        }
    

提交回复
热议问题