How to save attachments?

I am using MailKit / MimeKit 1.2.7 (latest NuGet version).

I've read the API documentation and several posts on stackoverflow. But I still couldn't successfully save the email attachments as a file.

Here is my current code:

var mimePart = (attachment as MimePart);
var memoryStream = new MemoryStream();
mimePart.ContentObject.DecodeTo(attachmentStream);

using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
      memoryStream.CopyTo(fileStream);
}

      

I have tried this code with various types of attachments. The created file on my disk is always empty.

What am I missing?

+3


source to share


1 answer


The problem with the above code is that you forget to reset memoryStream.Position

back to 0

: -)

However, the best way to do what you want to do is:



var mimePart = (attachment as MimePart);

using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
    mimePart.ContentObject.DecodeTo(fileStream);
}

      

In other words, there is no need to use a temporary memory stream.

+4


source







All Articles