Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save attachments?

Tags:

c#

mimekit

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?

like image 679
Ingmar Avatar asked Mar 05 '26 16:03

Ingmar


1 Answers

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.

like image 157
jstedfast Avatar answered Mar 08 '26 07:03

jstedfast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!