/// <summary> /// Parses the MessageBody as a Multipart message. /// This method will add these parts as Attachments /// </summary> private void ParseMultipartMessageBody() { string multipartBoundary = Headers.ContentType.Boundary; if (string.IsNullOrEmpty(multipartBoundary)) throw new ArgumentException("The body is a multipart message, but there is no multipart boundary"); int indexOfAttachmentStart = 0; bool moreParts = true; // Keep working until we have parsed every message part in this message while(moreParts) { // Find the start of the message parts multipartBoundary indexOfAttachmentStart = RawMessageBody.IndexOf(multipartBoundary, indexOfAttachmentStart); if(indexOfAttachmentStart == -1) throw new ArgumentException("The start of the attachment could not be found"); // Find the start of this message part - which does not include the multipartBoundary or the trailing CRLF indexOfAttachmentStart = indexOfAttachmentStart + multipartBoundary.Length + "\r\n".Length; // Find the end of the attachment, were we do not want the last line int indexOfAttachmentEnd = RawMessageBody.IndexOf(multipartBoundary, indexOfAttachmentStart); if(indexOfAttachmentEnd == -1) throw new ArgumentException("The end of the attachment could not be found"); // Check if this is the last part, which ends with the multipartBoundary followed by "--" if(RawMessageBody.Substring(indexOfAttachmentEnd).StartsWith(multipartBoundary + "--")) moreParts = false; // Calculate the length. We do not want to include the last "\r\n" in the attachment int attachmentLength = indexOfAttachmentEnd - indexOfAttachmentStart - "\r\n".Length; string messagePart = RawMessageBody.Substring(indexOfAttachmentStart, attachmentLength); Attachment att = new Attachment(messagePart, Headers); // Check if this is the MS-TNEF attachment type // which has ContentType application/ms-tnef // and also if we should decode it if(MIMETypes.IsMSTNEF(att.Headers.ContentType.MediaType) && AutoDecodeMSTNEF) { // It was a MS-TNEF attachment. Now we should parse it. TNEFParser tnef = new TNEFParser(att.DecodedAsBytes()); if (tnef.Parse()) { // ms-tnef attachment might contain multiple attachments inside it foreach (TNEFAttachment tatt in tnef.Attachments()) { Attachment attNew = new Attachment(tatt.FileContent, tatt.FileName, MIMETypes.GetMimeType(tatt.FileName)); Attachments.Add(attNew); } } else throw new ArgumentException("Could not parse TNEF attachment"); } else if(IsMIMEMailFile2(att)) { // The attachment itself is a multipart message // Parse it as such, and take the attachments from it // and add it to our message // This will in reality flatten the structure Message m = att.DecodeAsMessage(true,true); foreach (Attachment attachment in m.Attachments) Attachments.Add(attachment); } else { // This must be an attachment Attachments.Add(att); } } }