Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mimekit

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)
}
like image 470
Shak Ham Avatar asked Mar 04 '16 20:03

Shak Ham


1 Answers

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 ();
    }
}
like image 97
jstedfast Avatar answered Oct 21 '22 20:10

jstedfast