Get attachments in an array of bytes using MimeKit in C#

Shak Ham picture Shak Ham · Mar 4, 2016 · Viewed 7.1k times · Source

How can I get the attachment content when using MimeKit? This is what I have:

var mimeMessage = MimeMessage.Load(@"test.eml");
var attachments = mimeMessage.Attachments.ToList();

foreach (var attachment in attachments)
{
    // how do I get the content here (array of bytes or stream)
}

Answer

jstedfast picture jstedfast · Mar 4, 2016

This should do what you need:

var mimeMessage = MimeMessage.Load(@"test.eml");
var attachments = mimeMessage.Attachments.ToList();

foreach (var attachment in attachments)
{
    using (var memory = new MemoryStream ())
    {
        if (attachment is MimePart)
            ((MimePart) attachment).Content.DecodeTo (memory);
        else
            ((MessagePart) attachment).Message.WriteTo (memory);

        var bytes = memory.ToArray ();
    }
}