3

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

I have been reading the API documentation and several posts on stackoverflow. But I still wasn't able to successfully save 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 been trying this code with different kinds of attachments. The created file on my disc is always empty.

What am I missing?

Ingmar
  • 1,525
  • 6
  • 34
  • 51
  • Please see ["Should questions include “tags” in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"! –  Jul 15 '15 at 14:53

1 Answers1

5

The problem with the above code is that you are forgetting to reset the memoryStream.Position back to 0 :-)

However, a better way of doing what you want to do is this:

var mimePart = (attachment as MimePart);

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

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

jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • And this is the third and final question you helped me with today. And it's working perfectly too. I can't thank you enough for your help (and MailKit/MimeKit), Jeffrey. I got everything working now :) Have a nice day!! – Ingmar Jul 15 '15 at 18:37