8

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)
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shak Ham
  • 1,209
  • 2
  • 9
  • 27

2 Answers2

22

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 ();
    }
}
Neil
  • 1,613
  • 1
  • 16
  • 18
jstedfast
  • 35,744
  • 5
  • 97
  • 110
0

You can use WriteToStreamAsync method:

foreach (var attachment in message.Attachments)
{
    using var stream = new MemoryStream();
    attachment.WriteToStreamAsync(stream);
    var bytes = stream.ToArray();
}