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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With