private static MimeMessage ParseBody(LineOrientedStream stream, MimeHeaderCollection headers) { var message = new MimeMessage(headers); ParseContentType(message); ParseContentTransferEncoding(message); ParseContentDisposition(message); // read and parse content MemoryStream contentStream; if (message.MimeType == null || !message.MimeType.TypeEquals("multipart")) { contentStream = new MemoryStream(1024); stream.CopyTo(contentStream, MimeFormat.Standard.Folding); message.Content = contentStream; return message; } // multipart/* var parts = new List<MimeMessage>(); var delimiter = new ByteString("--" + message.Boundary); var closeDelimiter = new ByteString("--" + message.Boundary + "--"); MemoryStream body = null; ByteString line = null; ByteString lastLine = null; contentStream = new MemoryStream(1024); for (;;) { if (lastLine != null) contentStream.Write(lastLine.ByteArray, 0, lastLine.Length); var l = stream.ReadLine(); if (l == null) break; lastLine = line; line = new ByteString(l); if (line.StartsWith(delimiter)) { if (lastLine != null) { if (lastLine.EndsWith(Octets.CRLF)) // CRLF "--" boundary contentStream.Write(lastLine.ByteArray, 0, lastLine.Length - 2); else // LF "--" boundary or CR "--" boundary contentStream.Write(lastLine.ByteArray, 0, lastLine.Length - 1); } contentStream.Position = 0; if (body == null) body = contentStream; else parts.Add(Parse(contentStream)); if (line.StartsWith(closeDelimiter)) break; else contentStream = new MemoryStream(1024); lastLine = null; } } message.Content = body; message.SubParts.AddRange(parts); return message; }
private static MimeHeaderCollection ParseHeader(LineOrientedStream stream) { var headers = new MimeHeaderCollection(); MimeHeader current = null; for (;;) { var lineBytes = stream.ReadLine(false); if (lineBytes == null) break; // unexpected end of stream var line = new ByteString(lineBytes); if (line.IsEmpty) break; // end of headers if (line[0] == Octets.HT || line[0] == Octets.SP) { // LWSP-char // folding if (current == null) // ignore incorrect formed header continue; current.Value += Chars.SP; current.Value += line.TrimStart().ToString(); } else { // field = field-name ":" [ field-body ] CRLF // field-name = 1*<any CHAR, excluding CTLs, SPACE, and ":"> var delim = line.IndexOf(MimeHeader.NameBodyDelimiter); // ':' if (delim < 0) { // ignore incorrect formed header current = null; continue; } var header = new MimeHeader(line.Substring(0, delim).TrimEnd().ToString(), line.Substring(delim + 1).TrimStart().ToString()); headers.Add(header); current = header; } } return headers; }