/// <summary> /// Loads the text. /// </summary> /// <param name="header">The header.</param> /// <param name="body">The body.</param> /// <param name="contentType">Type of the content.</param> /// <returns></returns> private string LoadText(IReadOnlyCollection <string> header, List <string> body, string contentType) { var regexEncoding = new Regex(@"(?<=Content-Transfer-Encoding: )(\S*?)(?=$)"); var regexType = new Regex(@"(?<=Content-Type: )(.*?)(?=(;))"); if (string.Join(" ", header).Contains("Content-Transfer-Encoding: ")) { var type = regexType.Match((from line in header where line.StartsWith($"Content-Type: {contentType}") select line).FirstOrDefault() ?? "") .Value; if (type == "") { return($"Message Has No {contentType} Attached"); } var commonEncoding = regexEncoding.Match((from line in header where line.StartsWith("Content-Transfer-Encoding: ") select line).FirstOrDefault() ?? "") .Value; var res = string.Join("\r\n", body); return(MessageDecoder.DecodeBody(res, commonEncoding, "utf-8")); } var matching = (from line in body where line.StartsWith($"Content-Type: {contentType}") select line).FirstOrDefault(); if (matching == default(string)) { return($"Message Has No {contentType} Attached"); } var startOfHtml = body.IndexOf(matching) + 2; var boundary = (from line in body.Skip(startOfHtml) where line.StartsWith("--") && line[2] != '>' select line).FirstOrDefault(); int endOfHtml = body.IndexOf(boundary, startOfHtml); var encoding = regexEncoding.Match(body[startOfHtml - 1]).Value; var result = string.Join("\r\n", body.GetRange(startOfHtml, endOfHtml - startOfHtml)); string decodedBody = MessageDecoder.DecodeBody(result, encoding, "utf-8"); return(decodedBody); }
/// <summary> /// Parses the body header. /// </summary> /// <param name="uid">The uid.</param> /// <param name="response">The response.</param> /// <param name="subject">The subject.</param> /// <returns></returns> private MessageModel ParseBodyHeader(string uid, List <string> response, string subject) { var regex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); var email = new MessageModel(uid); var from = regex.Match((from line in response where line.StartsWith("From: ") select line) .FirstOrDefault() ?? "") .Value; var toMatches = regex.Matches((from line in response where line.StartsWith("To: ") select line) .FirstOrDefault() ?? ""); var to = (from Match item in toMatches select item.Value) .ToList(); var date = (from line in response where line.StartsWith("Date: ") select line.Replace("Date: ", string.Empty)) .FirstOrDefault(); DateTime parsedDate = default(DateTime); if (date != null) { date = date.Contains("(") ? date.Substring(0, date.Length - 5) : date; parsedDate = Convert.ToDateTime(date); } var regexSubj = new Regex(@"(?<=Subject: )([\s\S]*?)(?=$)"); string subj = regexSubj.Match(subject).Value; email.Subject = MessageDecoder.DecodeEncodedLine(subj); email.From = from; email.To = to; email.Date = parsedDate; return(email); }