Example #1
0
 /// <summary>
 /// Parses the ms-tnef stream from the provided <see cref="System.IO.Stream" />.
 /// </summary>
 /// <param name="path">A <see cref="System.String" /> specifying the path on which to save the attachments found. Specify the <b>null</b> reference to save them in memory as  <see cref="System.IO.MemoryStream" /> instances instead.</param>
 /// <returns><b>true</b> if parsing is successful. <b>false</b> otherwise.</returns>
 public bool Parse( System.String path )
 {
     if ( this._reader==null || !this._reader.BaseStream.CanRead )
         return false;
     int sig = this.ReadInt();
     if ( sig!=TnefSignature ) {
     #if LOG
         if ( logger.IsErrorEnabled )
             logger.Error(System.String.Concat("Tnef signature not matched [", sig, "]<>[", TnefSignature, "]"));
     #endif
         return false;
     }
     bool error = false;
     this._attachments = new System.Collections.ArrayList();
     ushort key = this.ReadUInt16();
     System.Text.Encoding enc = anmar.SharpMimeTools.SharpMimeHeader.EncodingDefault;
     anmar.SharpMimeTools.SharpAttachment attachment_cur = null;
     for ( System.Byte cur=this.ReadByte(); cur!=System.Byte.MinValue; cur=ReadByte() ) {
         TnefLvlType lvl = (TnefLvlType)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefLvlType), cur, TnefLvlType.Unknown);
         // Type
         int type = this.ReadInt();
         // Size
         int size = this.ReadInt();
         // Attibute name and type
         TnefAttribute att_n = (TnefAttribute)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefAttribute), (ushort)((type<<16)>>16), TnefAttribute.Unknown);
         TnefDataType att_t = (TnefDataType)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefDataType), (ushort)(type>>16), TnefDataType.Unknown);
         if ( lvl==TnefLvlType.Unknown || att_n==TnefAttribute.Unknown || att_t==TnefDataType.Unknown ) {
     #if LOG
         if ( logger.IsErrorEnabled )
             logger.Error(System.String.Concat("Attribute data is not valid [", lvl ,"] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "]"));
     #endif
             error = true;
             break;
         }
         // Read data
         System.Byte[] buffer = this.ReadBytes(size);
         // Read checkSum
         ushort checksum = this.ReadUInt16();
         // Verify checksum
         if ( !this.VerifyChecksum(buffer, checksum) ) {
     #if LOG
         if ( logger.IsErrorEnabled )
             logger.Error(System.String.Concat("Checksum validation failed [", lvl ,"] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "(", (buffer!=null)?buffer.Length:0, ")] [checksum=", checksum, "]"));
     #endif
             error = true;
             break;
         }
         size = buffer.Length;
     #if LOG
         if ( logger.IsDebugEnabled )
             logger.Debug(System.String.Concat("[", lvl ,"] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "(", (buffer!=null)?buffer.Length:0, ")] [checksum=", checksum, "]"));
     #endif
         if ( lvl==TnefLvlType.Message ) {
             // Text body
             if ( att_n==TnefAttribute.Body ) {
                 if ( att_t==TnefDataType.atpString ) {
                     this._body = enc.GetString(buffer, 0, size);
                 }
             // Message mapi props (html body, rtf body, ...)
             } else if ( att_n==TnefAttribute.MapiProps ) {
                 this.ReadMapi(buffer, size);
             // Stream Codepage
             } else if ( att_n==TnefAttribute.OEMCodepage ) {
                 uint codepage1 = (uint)(buffer[0] + (buffer[1]<<8)  +(buffer[2]<<16) + (buffer[3]<<24));
                 if ( codepage1>0 ) {
                     try {
                         enc = System.Text.Encoding.GetEncoding((int)codepage1);
     #if LOG
                         if ( logger.IsDebugEnabled ) {
                             logger.Debug(System.String.Concat("Now using [", enc.EncodingName, "] encoding to decode strings."));
                         }
     #endif
                     } catch ( System.Exception ) {}
                 }
             }
         } else if ( lvl==TnefLvlType.Attachment ) {
             // Attachment start
             if ( att_n==TnefAttribute.AttachRendData ) {
                 System.String name = System.String.Concat("generated_", key, "_", (this._attachments.Count+1), ".binary" );
                 if ( path==null ) {
                     attachment_cur = new anmar.SharpMimeTools.SharpAttachment(new System.IO.MemoryStream());
                 } else {
                     attachment_cur = new anmar.SharpMimeTools.SharpAttachment(new System.IO.FileInfo(System.IO.Path.Combine(path, name)));
                 }
                 attachment_cur.Name = name;
             // Attachment name
             } else if ( att_n==TnefAttribute.AttachTitle ) {
                 if ( attachment_cur!=null && att_t==TnefDataType.atpString && buffer!=null && this._attachments.Count>0 ) {
                     // NULL terminated string
                     if ( buffer[size-1]=='\0' ) {
                         size--;
                     }
                     if ( size>0 ) {
                         System.String name = enc.GetString(buffer, 0, size);
                         if ( name.Length>0 ) {
                             attachment_cur.Name = name;
                             // Content already saved, so we have to rename
                             if ( attachment_cur.SavedFile!=null && attachment_cur.SavedFile.Exists ) {
                                 try {
                                     attachment_cur.SavedFile.MoveTo(System.IO.Path.Combine(path, attachment_cur.Name));
                                 } catch ( System.Exception ) {}
                             }
                         }
                     }
                 }
             // Modification and creation date
             } else if ( att_n==TnefAttribute.AttachModifyDate || att_n==TnefAttribute.AttachCreateDate ) {
                 if ( attachment_cur!=null && att_t==TnefDataType.atpDate && buffer!=null && size==14 ) {
                     int pos = 0;
                     System.DateTime date = new System.DateTime((buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)), (buffer[pos++]+(buffer[pos++]<<8)));
                     if ( att_n==TnefAttribute.AttachModifyDate ) {
                         attachment_cur.LastWriteTime = date;
                     } else if ( att_n==TnefAttribute.AttachCreateDate ) {
                         attachment_cur.CreationTime = date;
                     }
                 }
             // Attachment data
             } else if ( att_n==TnefAttribute.AttachData ) {
                 if ( attachment_cur!=null && att_t==TnefDataType.atpByte && buffer!=null ) {
                     if ( attachment_cur.SavedFile!=null ) {
                         System.IO.FileStream stream = null;
                         try {
                             stream = attachment_cur.SavedFile.OpenWrite();
                         } catch ( System.Exception e ) {
     #if LOG
                             if ( logger.IsErrorEnabled )
                                 logger.Error(System.String.Concat("Error writting file [", attachment_cur.SavedFile.FullName, "]"), e);
     #endif
                             error = true;
                             break;
                         }
                         stream.Write(buffer, 0, size);
                         stream.Flush();
                         attachment_cur.Size = stream.Length;
                         stream.Close();
                         stream = null;
                         attachment_cur.SavedFile.Refresh();
                         // Is name has changed, we have to rename
                         if ( attachment_cur.SavedFile.Name!=attachment_cur.Name )
                             try {
                                 attachment_cur.SavedFile.MoveTo(System.IO.Path.Combine(path, attachment_cur.Name));
                             } catch ( System.Exception ) {}
                     } else {
                         attachment_cur.Stream.Write(buffer, 0, size);
                         attachment_cur.Stream.Flush();
                         attachment_cur.Size = attachment_cur.Stream.Length;
                     }
                     this._attachments.Add(attachment_cur);
                 }
             // Attachment mapi props
             } else if ( att_n==TnefAttribute.Attachment ) {
                 this.ReadMapi(buffer, size);
             }
         }
     }
     if ( this._attachments.Count==0 )
         this._attachments = null;
     return !error;
 }
Example #2
0
 private void ParseMessage( anmar.SharpMimeTools.SharpMimeMessage part, anmar.SharpMimeTools.MimeTopLevelMediaType types, bool html, SharpDecodeOptions options, System.String preferredtextsubtype, System.String path )
 {
     if ( (types&part.Header.TopLevelMediaType)!=part.Header.TopLevelMediaType ) {
     #if LOG
         if ( log.IsDebugEnabled )
             log.Debug (System.String.Concat("Mime-Type [", part.Header.TopLevelMediaType, "] is not an accepted Mime-Type. Skiping part."));
     #endif
         return;
     }
     switch ( part.Header.TopLevelMediaType ) {
         case anmar.SharpMimeTools.MimeTopLevelMediaType.multipart:
         case anmar.SharpMimeTools.MimeTopLevelMediaType.message:
             // TODO: allow other subtypes of "message"
             // Only message/rfc822 allowed, other subtypes ignored
             if ( part.Header.TopLevelMediaType.Equals(anmar.SharpMimeTools.MimeTopLevelMediaType.message)
                  && !part.Header.SubType.Equals("rfc822") )
                 break;
             if ( part.Header.SubType.Equals ("alternative") ) {
                 if ( part.PartsCount>0 ) {
                     anmar.SharpMimeTools.SharpMimeMessage altenative = null;
                     // Get the first mime part of the alternatives that has a accepted Mime-Type
                     for ( int i=part.PartsCount; i>0; i-- ) {
                         anmar.SharpMimeTools.SharpMimeMessage item = part.GetPart(i-1);
                         if ( (types&part.Header.TopLevelMediaType)!=part.Header.TopLevelMediaType
                             || ( !html && item.Header.TopLevelMediaType.Equals(anmar.SharpMimeTools.MimeTopLevelMediaType.text) && item.Header.SubType.Equals("html") )
                            ) {
     #if LOG
                            	if ( log.IsDebugEnabled )
                            		log.Debug (System.String.Concat("Mime-Type [", item.Header.TopLevelMediaType, "/", item.Header.SubType, "] is not an accepted Mime-Type. Skiping alternative part."));
     #endif
                             continue;
                         }
                         // First allowed one.
                         if ( altenative==null ) {
                             altenative=item;
                             // We don't have to select body part based on subtype if not asked for, or not a text one
                             // or it's already the preferred one
                             if ( preferredtextsubtype==null || item.Header.TopLevelMediaType!=anmar.SharpMimeTools.MimeTopLevelMediaType.text || (preferredtextsubtype!=null && item.Header.SubType==preferredtextsubtype) ) {
                                 break;
                             }
                         // This one is preferred over the last part
                         } else if ( preferredtextsubtype!=null && item.Header.TopLevelMediaType==anmar.SharpMimeTools.MimeTopLevelMediaType.text && item.Header.SubType==preferredtextsubtype ) {
                             altenative=item;
                             break;
                         }
                     }
                     if ( altenative!=null ) {
                         // If message body as html is allowed and part has a Content-ID field
                         // add an anchor to mark this body part
                         if ( html && part.Header.Contains("Content-ID") && (options&anmar.SharpMimeTools.SharpDecodeOptions.NamedAnchors)==anmar.SharpMimeTools.SharpDecodeOptions.NamedAnchors ) {
                             // There is a previous text body, so enclose it in <pre>
                             if ( !this._body_html && this._body.Length>0 ) {
                                 this._body = System.String.Concat ("<pre>", System.Web.HttpUtility.HtmlEncode(this._body), "</pre>");
                                 this._body_html = true;
                             }
                             // Add the anchor
                             this._body = System.String.Concat (this._body, "<a name=\"", anmar.SharpMimeTools.SharpMimeTools.Rfc2392Url(this.MessageID), "_", anmar.SharpMimeTools.SharpMimeTools.Rfc2392Url(part.Header.ContentID), "\"></a>");
                         }
                         this.ParseMessage(altenative, types, html, options, preferredtextsubtype, path);
                     }
                 }
             // TODO: Take into account each subtype of "multipart"
             } else if ( part.PartsCount>0 ) {
                 foreach ( anmar.SharpMimeTools.SharpMimeMessage item in part ) {
                     this.ParseMessage(item, types, html, options, preferredtextsubtype, path);
                 }
             }
             break;
         case anmar.SharpMimeTools.MimeTopLevelMediaType.text:
             if ( ( part.Disposition==null || !part.Disposition.Equals("attachment") )
                 && ( part.Header.SubType.Equals("plain") || part.Header.SubType.Equals("html") ) ) {
                 bool body_was_html = this._body_html;
                 // HTML content not allowed
                 if ( part.Header.SubType.Equals("html") ) {
                     if ( !html )
                         break;
                     else
                         this._body_html=true;
                 }
                 if ( html && part.Header.Contains("Content-ID") && (options&anmar.SharpMimeTools.SharpDecodeOptions.NamedAnchors)==anmar.SharpMimeTools.SharpDecodeOptions.NamedAnchors ) {
                     this._body_html = true;
                 }
                 if ( this._body_html && !body_was_html && this._body.Length>0 ) {
                     this._body = System.String.Concat ("<pre>", System.Web.HttpUtility.HtmlEncode(this._body), "</pre>");
                 }
                 // If message body is html and this part has a Content-ID field
                 // add an anchor to mark this body part
                 if ( this._body_html && part.Header.Contains("Content-ID") && (options&anmar.SharpMimeTools.SharpDecodeOptions.NamedAnchors)==anmar.SharpMimeTools.SharpDecodeOptions.NamedAnchors ) {
                     this._body = System.String.Concat (this._body, "<a name=\"", anmar.SharpMimeTools.SharpMimeTools.Rfc2392Url(this.MessageID), "_", anmar.SharpMimeTools.SharpMimeTools.Rfc2392Url(part.Header.ContentID), "\"></a>");
                 }
                 if ( this._body_html && part.Header.SubType.Equals("plain") ) {
                     this._body = System.String.Concat (this._body, "<pre>", System.Web.HttpUtility.HtmlEncode(part.BodyDecoded), "</pre>");
                 } else
                     this._body = System.String.Concat (this._body, part.BodyDecoded);
             } else {
                 if ( (types&anmar.SharpMimeTools.MimeTopLevelMediaType.application)!=anmar.SharpMimeTools.MimeTopLevelMediaType.application ) {
     #if LOG
                     if ( log.IsDebugEnabled )
                         log.Debug (System.String.Concat("Mime-Type [", anmar.SharpMimeTools.MimeTopLevelMediaType.application, "] is not an accepted Mime-Type. Skiping part."));
     #endif
                     return;
                 }
                 goto case anmar.SharpMimeTools.MimeTopLevelMediaType.application;
             }
             break;
         case anmar.SharpMimeTools.MimeTopLevelMediaType.application:
         case anmar.SharpMimeTools.MimeTopLevelMediaType.audio:
         case anmar.SharpMimeTools.MimeTopLevelMediaType.image:
         case anmar.SharpMimeTools.MimeTopLevelMediaType.video:
             // Attachments not allowed.
             if ( (options&anmar.SharpMimeTools.SharpDecodeOptions.AllowAttachments)!=anmar.SharpMimeTools.SharpDecodeOptions.AllowAttachments )
                 break;
             anmar.SharpMimeTools.SharpAttachment attachment = null;
             // Save to a file
             if ( path!=null ) {
                 System.IO.FileInfo file = part.DumpBody(path, true);
                 if ( file!=null ) {
                     attachment = new anmar.SharpMimeTools.SharpAttachment(file);
                     attachment.Name = file.Name;
                     attachment.Size = file.Length;
                 }
             // Save to a stream
             } else {
                 System.IO.MemoryStream stream = new System.IO.MemoryStream();
                 if ( part.DumpBody(stream) ) {
                     attachment = new anmar.SharpMimeTools.SharpAttachment(stream);
                     if ( part.Name!=null )
                         attachment.Name = part.Name;
                     else
                         attachment.Name = System.String.Concat("generated_", part.GetHashCode(), ".", part.Header.SubType);
                     attachment.Size = stream.Length;
                 }
                 stream = null;
             }
             if ( attachment!=null && part.Header.SubType=="ms-tnef" && (options&anmar.SharpMimeTools.SharpDecodeOptions.DecodeTnef)==anmar.SharpMimeTools.SharpDecodeOptions.DecodeTnef ) {
             // Try getting attachments form a tnef stream
     #if LOG
                 if ( log.IsDebugEnabled ) {
                     log.Debug(System.String.Concat("Decoding ms-tnef stream."));
                 }
     #endif
                 System.IO.Stream stream = attachment.Stream;
                 if ( stream!=null && stream.CanSeek )
                     stream.Seek(0, System.IO.SeekOrigin.Begin);
                 anmar.SharpMimeTools.SharpTnefMessage tnef = new anmar.SharpMimeTools.SharpTnefMessage(stream);
                 if ( tnef.Parse(path) ) {
                     if ( tnef.Attachments!=null ) {
                         this._attachments.AddRange(tnef.Attachments);
                     }
                     attachment.Close();
                     // Delete the raw tnef file
                     if ( attachment.SavedFile!=null ) {
                         if ( stream!=null && stream.CanRead )
                             stream.Close();
                         attachment.SavedFile.Delete();
                     }
                     attachment = null;
                     tnef.Close();
     #if LOG
                     if ( log.IsDebugEnabled ) {
                         log.Debug(System.String.Concat("ms-tnef stream decoded successfully. Found [", ((tnef.Attachments!=null)?tnef.Attachments.Count:0),"] attachments."));
                     }
     #endif
                 } else {
                     // The read-only stream is no longer needed and locks the file
                     if ( attachment.SavedFile!=null && stream!=null && stream.CanRead )
                         stream.Close();
                 }
                 stream = null;
                 tnef = null;
             }
             if ( attachment!=null ) {
                 if ( part.Disposition!=null && part.Disposition=="inline" ) {
                     attachment.Inline = true;
                 }
                 attachment.MimeTopLevelMediaType = part.Header.TopLevelMediaType;
                 attachment.MimeMediaSubType = part.Header.SubType;
                 // Store attachment's CreationTime
                 if ( part.Header.ContentDispositionParameters.ContainsKey("creation-date") )
                     attachment.CreationTime = anmar.SharpMimeTools.SharpMimeTools.parseDate ( part.Header.ContentDispositionParameters["creation-date"] );
                 // Store attachment's LastWriteTime
                 if ( part.Header.ContentDispositionParameters.ContainsKey("modification-date") )
                     attachment.LastWriteTime = anmar.SharpMimeTools.SharpMimeTools.parseDate ( part.Header.ContentDispositionParameters["modification-date"] );
                 if ( part.Header.Contains("Content-ID") )
                     attachment.ContentID = part.Header.ContentID;
                 this._attachments.Add(attachment);
             }
             break;
         default:
             break;
     }
 }
Example #3
0
 private void UuDecode( System.String path )
 {
     if ( this._body.Length==0 || this._body.IndexOf("begin ")==-1 || this._body.IndexOf("end")==-1 )
         return;
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     System.IO.StringReader reader = new System.IO.StringReader(this._body);
     System.IO.Stream stream = null;
     anmar.SharpMimeTools.SharpAttachment attachment = null;
     for ( System.String line=reader.ReadLine(); line!=null; line=reader.ReadLine() ) {
         if ( stream==null ) {
             // Found the start point of uuencoded content
             if ( line.Length>10 && line[0]=='b' && line[1]=='e' && line[2]=='g' && line[3]=='i' && line[4]=='n' && line[5]==' ' && line[9]==' ' ) {
                 System.String name = System.IO.Path.GetFileName(line.Substring(10));
     #if LOG
                 if ( log.IsDebugEnabled )
                     log.Debug (System.String.Concat("uuencoded content found. name[", name, "]"));
     #endif
                 // In-Memory decoding
                 if ( path==null ) {
                     attachment = new anmar.SharpMimeTools.SharpAttachment(new System.IO.MemoryStream());
                     stream = attachment.Stream;
                 // Filesystem decoding
                 } else {
                     attachment = new anmar.SharpMimeTools.SharpAttachment(new System.IO.FileInfo(System.IO.Path.Combine(path, name)));
                     stream = attachment.SavedFile.OpenWrite();
                 }
                 attachment.Name = name;
             // Not uuencoded line, so add it to new body
             } else {
                 sb.Append(line);
                 sb.Append(System.Environment.NewLine);
             }
         } else {
             // Content finished
             if ( line.Length==3 && line=="end" ) {
                 stream.Flush();
                 if (  stream.Length>0 ) {
     #if LOG
                     if ( log.IsDebugEnabled )
                         log.Debug (System.String.Concat("uuencoded content finished. name[", attachment.Name, "] size[", stream.Length, "]"));
     #endif
                     attachment.Size = stream.Length;
                     this._attachments.Add(attachment);
                 }
                 // When decoding to a file, close the stream.
                 if ( attachment.SavedFile!=null || stream.Length==0 ) {
                     stream.Close();
                 }
                 attachment = null;
                 stream = null;
             // Decode and write uuencoded line
             } else {
                 anmar.SharpMimeTools.SharpMimeTools.UuDecodeLine(line, stream);
             }
         }
     }
     if ( stream!=null && stream.CanRead ) {
         stream.Close();
         stream = null;
     }
     reader.Close();
     reader = null;
     this._body = sb.ToString();
     sb = null;
 }
Example #4
0
        /// <summary>
        /// Parses the ms-tnef stream from the provided <see cref="System.IO.Stream" />.
        /// </summary>
        /// <param name="path">A <see cref="System.String" /> specifying the path on which to save the attachments found. Specify the <b>null</b> reference to save them in memory as  <see cref="System.IO.MemoryStream" /> instances instead.</param>
        /// <returns><b>true</b> if parsing is successful. <b>false</b> otherwise.</returns>
        public bool Parse(System.String path)
        {
            if (this._reader == null || !this._reader.BaseStream.CanRead)
            {
                return(false);
            }
            int sig = this.ReadInt();

            if (sig != TnefSignature)
            {
#if LOG
                if (logger.IsErrorEnabled)
                {
                    logger.Error(System.String.Concat("Tnef signature not matched [", sig, "]<>[", TnefSignature, "]"));
                }
#endif
                return(false);
            }
            bool error = false;
            this._attachments = new System.Collections.ArrayList();
            ushort key = this.ReadUInt16();
            System.Text.Encoding enc = anmar.SharpMimeTools.SharpMimeHeader.EncodingDefault;
            anmar.SharpMimeTools.SharpAttachment attachment_cur = null;
            for (System.Byte cur = this.ReadByte(); cur != System.Byte.MinValue; cur = ReadByte())
            {
                TnefLvlType lvl = (TnefLvlType)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefLvlType), cur, TnefLvlType.Unknown);
                // Type
                int type = this.ReadInt();
                // Size
                int size = this.ReadInt();
                // Attibute name and type
                TnefAttribute att_n = (TnefAttribute)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefAttribute), (ushort)((type << 16) >> 16), TnefAttribute.Unknown);
                TnefDataType  att_t = (TnefDataType)anmar.SharpMimeTools.SharpMimeTools.ParseEnum(typeof(TnefDataType), (ushort)(type >> 16), TnefDataType.Unknown);
                if (lvl == TnefLvlType.Unknown || att_n == TnefAttribute.Unknown || att_t == TnefDataType.Unknown)
                {
#if LOG
                    if (logger.IsErrorEnabled)
                    {
                        logger.Error(System.String.Concat("Attribute data is not valid [", lvl, "] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "]"));
                    }
#endif
                    error = true;
                    break;
                }
                // Read data
                System.Byte[] buffer = this.ReadBytes(size);
                // Read checkSum
                ushort checksum = this.ReadUInt16();
                // Verify checksum
                if (!this.VerifyChecksum(buffer, checksum))
                {
#if LOG
                    if (logger.IsErrorEnabled)
                    {
                        logger.Error(System.String.Concat("Checksum validation failed [", lvl, "] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "(", (buffer != null)?buffer.Length:0, ")] [checksum=", checksum, "]"));
                    }
#endif
                    error = true;
                    break;
                }
                size = buffer.Length;
#if LOG
                if (logger.IsDebugEnabled)
                {
                    logger.Debug(System.String.Concat("[", lvl, "] [type=", type, "->(", att_n, ",", att_t, ")] [size=", size, "(", (buffer != null)?buffer.Length:0, ")] [checksum=", checksum, "]"));
                }
#endif
                if (lvl == TnefLvlType.Message)
                {
                    // Text body
                    if (att_n == TnefAttribute.Body)
                    {
                        if (att_t == TnefDataType.atpString)
                        {
                            this._body = enc.GetString(buffer, 0, size);
                        }
                        // Message mapi props (html body, rtf body, ...)
                    }
                    else if (att_n == TnefAttribute.MapiProps)
                    {
                        this.ReadMapi(buffer, size);
                        // Stream Codepage
                    }
                    else if (att_n == TnefAttribute.OEMCodepage)
                    {
                        uint codepage1 = (uint)(buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24));
                        if (codepage1 > 0)
                        {
                            try {
                                enc = System.Text.Encoding.GetEncoding((int)codepage1);
#if LOG
                                if (logger.IsDebugEnabled)
                                {
                                    logger.Debug(System.String.Concat("Now using [", enc.EncodingName, "] encoding to decode strings."));
                                }
#endif
                            } catch (System.Exception) {}
                        }
                    }
                }
                else if (lvl == TnefLvlType.Attachment)
                {
                    // Attachment start
                    if (att_n == TnefAttribute.AttachRendData)
                    {
                        System.String name = System.String.Concat("generated_", key, "_", (this._attachments.Count + 1), ".binary");
                        if (path == null)
                        {
                            attachment_cur = new anmar.SharpMimeTools.SharpAttachment(new System.IO.MemoryStream());
                        }
                        else
                        {
                            attachment_cur = new anmar.SharpMimeTools.SharpAttachment(new System.IO.FileInfo(System.IO.Path.Combine(path, name)));
                        }
                        attachment_cur.Name = name;
                        // Attachment name
                    }
                    else if (att_n == TnefAttribute.AttachTitle)
                    {
                        if (attachment_cur != null && att_t == TnefDataType.atpString && buffer != null)
                        {
                            // NULL terminated string
                            if (buffer[size - 1] == '\0')
                            {
                                size--;
                            }
                            if (size > 0)
                            {
                                System.String name = enc.GetString(buffer, 0, size);
                                if (name.Length > 0)
                                {
                                    attachment_cur.Name = name;
                                    // Content already saved, so we have to rename
                                    if (attachment_cur.SavedFile != null && attachment_cur.SavedFile.Exists)
                                    {
                                        try {
                                            attachment_cur.SavedFile.MoveTo(System.IO.Path.Combine(path, attachment_cur.Name));
                                        } catch (System.Exception) {}
                                    }
                                }
                            }
                        }
                        // Modification and creation date
                    }
                    else if (att_n == TnefAttribute.AttachModifyDate || att_n == TnefAttribute.AttachCreateDate)
                    {
                        if (attachment_cur != null && att_t == TnefDataType.atpDate && buffer != null && size == 14)
                        {
                            int             pos  = 0;
                            System.DateTime date = new System.DateTime((buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)), (buffer[pos++] + (buffer[pos++] << 8)));
                            if (att_n == TnefAttribute.AttachModifyDate)
                            {
                                attachment_cur.LastWriteTime = date;
                            }
                            else if (att_n == TnefAttribute.AttachCreateDate)
                            {
                                attachment_cur.CreationTime = date;
                            }
                        }
                        // Attachment data
                    }
                    else if (att_n == TnefAttribute.AttachData)
                    {
                        if (attachment_cur != null && att_t == TnefDataType.atpByte && buffer != null)
                        {
                            if (attachment_cur.SavedFile != null)
                            {
                                System.IO.FileStream stream = null;
                                try {
                                    stream = attachment_cur.SavedFile.OpenWrite();
                                } catch (System.Exception) {
#if LOG
                                    if (logger.IsErrorEnabled)
                                    {
                                        logger.Error(System.String.Concat("Error writting file [", attachment_cur.SavedFile.FullName, "]"), e);
                                    }
#endif
                                    error = true;
                                    break;
                                }
                                stream.Write(buffer, 0, size);
                                stream.Flush();
                                attachment_cur.Size = stream.Length;
                                stream.Close();
                                stream = null;
                                attachment_cur.SavedFile.Refresh();
                                // Is name has changed, we have to rename
                                if (attachment_cur.SavedFile.Name != attachment_cur.Name)
                                {
                                    try {
                                        attachment_cur.SavedFile.MoveTo(System.IO.Path.Combine(path, attachment_cur.Name));
                                    } catch (System.Exception) {}
                                }
                            }
                            else
                            {
                                attachment_cur.Stream.Write(buffer, 0, size);
                                attachment_cur.Stream.Flush();
                                attachment_cur.Size = attachment_cur.Stream.Length;
                            }
                            this._attachments.Add(attachment_cur);
                        }
                        // Attachment mapi props
                    }
                    else if (att_n == TnefAttribute.Attachment)
                    {
                        this.ReadMapi(buffer, size);
                    }
                }
            }
            if (this._attachments.Count == 0)
            {
                this._attachments = null;
            }
            return(!error);
        }