Search code examples
c#mimekit

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


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)
}

Solution

  • 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 ();
        }
    }