Best way to parse string of email addresses

后端 未结 13 2615
悲哀的现实
悲哀的现实 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:06

    Here's what I came up with. It assumes that a valid email address must have one and only one '@' sign in it:

        public List ParseAddresses(string field)
        {
            var tokens = field.Split(',');
            var addresses = new List();
    
            var tokenBuffer = new List();
    
            foreach (var token in tokens)
            {
                tokenBuffer.Add(token);
    
                if (token.IndexOf("@", StringComparison.Ordinal) > -1)
                {
                    addresses.Add( string.Join( ",", tokenBuffer));
                    tokenBuffer.Clear();
                }
            }
    
            return addresses.Select(t => new MailAddress(t)).ToList();
        }
    

提交回复
热议问题