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

2 Answers 2

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 ();
    }
}
4
  • What if the content type is "message/rfc822" (the attachment is an email)? That didn't seem to work with that type of attachments.
    – Shak Ham
    Mar 4, 2016 at 21:45
  • Just one question, will those two options cover any type of attachment?
    – Shak Ham
    Mar 4, 2016 at 21:57
  • Is there a way to get the unique id of the attachment? (not the Content Id)
    – Shak Ham
    Mar 4, 2016 at 21:58
  • Yes, they'll cover all types of attachments. Attachments don't have unique ids, the closest they have is the Content-Id.
    – jstedfast
    Mar 4, 2016 at 23:28
0

You can use WriteToStreamAsync method:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.