26

I'm try save attachments from message

foreach(MimeKit.MimeEntity at message.Attachments) 
{
    at.WriteTo("nameFile");
}

File saved, but when I open I get the error the file is corrupted or too large The size of this file is 88 kb, but size of the file should be equal to 55 kb.

I think that in all recorded message file.

How do I only record the attachment?

MailKit v1.2.0.0 MimeKit 1.2.0.0

vela
  • 147
  • 10
sergpc
  • 305
  • 1
  • 4
  • 11

1 Answers1

54

You are saving the entire MIME object (including the headers). What you need to do is save the content.

foreach (var attachment in message.Attachments) {
    using (var stream = File.Create ("fileName")) {
        if (attachment is MessagePart) {
            var part = (MessagePart) attachment;

            part.Message.WriteTo (stream);
        } else {
            var part = (MimePart) attachment;

            part.Content.DecodeTo (stream);
        }
    }
}
starball
  • 20,030
  • 7
  • 43
  • 238
jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • var part = (MimeKit.MessagePart)attachment; here I get an exception "Failed to bring the object type MimeKit.MimePart type MimeKit.MessagePart – sergpc Mar 26 '16 at 09:31
  • part.ContentObject.DecodeTo(stream); and here i get error: "MimeKit.MessageParts" does not contain a definition for "Content_Object". Unable to find a method of expansion "ContentObject", receiving a first argument of type "MimeKit.MessagePart" (missing using directive or an assembly reference?) can be a problem in versions? – sergpc Mar 26 '16 at 09:33
  • what is your version MimeKit and MailKit? – sergpc Mar 26 '16 at 09:36
  • You did not copy my code correctly if you got those exceptions because MessagePart does not have a ContentObject property, only MimePart does. – jstedfast Mar 26 '16 at 11:16
  • 6
    Each `MimeEntity` in the `message.Attachments` enumeration can be either a `MimePart` or a `MessagePart`. `MessagePart` items have a `.Message` property that represents the content while `MimePart` objects have a `ContentObject` that represent the content. – jstedfast Mar 26 '16 at 11:19
  • @jstedfast I noticed that not all attachments are always listed in the message.Attachments (like inline pdf files) . Can we be sure that all pdf/image attachments are processed when using message.BodyParts that have a MimePart.FileName ? – MichaelD Mar 27 '18 at 13:04
  • Hi there @jstedfast ! Seems that ContentObject is actually deprecated. I'm trying to get the attachment's data as a `byte[]` but `part.Content.Stream.CopyTo(memoryStream)` is actually saving the whole MIME entity. Any handful way to go? Thanks. – Gonzo345 Jan 14 '19 at 08:55
  • `part.Content.DecodeTo(memoryStream)` is what you want. `part.Content.Stream.CopyTo()` will copy the base64 encoded content to the memory stream which is probably what you are mistaking for "the whole MIME entity". – jstedfast Jun 16 '21 at 12:28