public static ImapEnvelope Parse(string text) { // Escape nested quotes. // TODO: Should be included in the regex. text = text.Replace("\\\"", "%%%"); var envelope = new ImapEnvelope(); var matches = FetchMetaRegex.Matches(text); foreach (Match match in matches) { if (match.Value.StartsWith("RFC822.SIZE", StringComparison.InvariantCultureIgnoreCase)) { envelope.Size = long.Parse(match.Value.Split(' ').Last()); continue; } if (match.Value.StartsWith("UID", StringComparison.InvariantCultureIgnoreCase)) { envelope.Uid = long.Parse(match.Value.Split(' ').Last()); continue; } if (match.Value.StartsWith("INTERNALDATE", StringComparison.InvariantCultureIgnoreCase)) { var date = DateRegex.Match(match.Value).Value; envelope.InternalDate = DateTime.Parse(date); continue; } if (match.Value.StartsWith("FLAGS", StringComparison.InvariantCultureIgnoreCase)) { const string pattern = @"\\[A-za-z0-9\*]+"; var flags = Regex.Matches(match.Value, pattern, RegexOptions.CultureInvariant) .Cast <Match>() .Select(x => x.Value); envelope.AddFlags(flags); } } String[] t = { "ENVELOPE" }; var temp = text.Split(t, StringSplitOptions.None); matches = EnvelopeRegex.Matches(temp[1]); envelope.Subject = TransferEncoder.Decode(matches[1].Value) .TrimQuotes() .Replace("%%%", "\""); envelope.AddContactsToFrom(ParseContacts(matches[2].Value)); envelope.AddContactsToSender(ParseContacts(matches[3].Value)); envelope.ReplyTo = ParseContacts(matches[4].Value).FirstOrDefault(); envelope.AddContactsToRecipients(ParseContacts(matches[5].Value)); envelope.AddContactsToCc(ParseContacts(matches[6].Value)); envelope.AddContactsToBcc(ParseContacts(matches[7].Value)); envelope.InReplyTo = matches[8].Value.TrimQuotes().TrimNil(); envelope.MessageId = matches[9].Value.TrimQuotes().TrimNil(); return(envelope); }
private static IEnumerable <MailAddress> ParseContacts(string value) { var trimmed = value.TrimAny(1).TrimQuotes(); var entries = Regex.Matches(trimmed, "\\\"\\\"|\\\".+?\\\"|NIL"); var contacts = entries .OfType <Match>() .Select(x => x.Value.Trim(new[] { '"', '\\' })) .Bundle(4).ToArray() .ToArray(); return(from contact in contacts select contact.ToArray() into items let name = TransferEncoder.Decode(items[0]) let address = string.Format("{0}@{1}", items[2], items[3]) where !string.IsNullOrEmpty(items[3]) select new MailAddress(address, name)); }