Get attachments in an array of bytes using MimeKit in C#
Asked Answered
P

2

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)
}
Palaeozoic answered 4/3, 2016 at 20:57 Comment(0)
E
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 ();
    }
}
Exhibitionism answered 4/3, 2016 at 21:32 Comment(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.Palaeozoic
Just one question, will those two options cover any type of attachment?Palaeozoic
Is there a way to get the unique id of the attachment? (not the Content Id)Palaeozoic
Yes, they'll cover all types of attachments. Attachments don't have unique ids, the closest they have is the Content-Id.Exhibitionism
S
0

You can use WriteToStreamAsync method:

foreach (var attachment in message.Attachments)
{
    using var stream = new MemoryStream();
    attachment.WriteToStreamAsync(stream);
    var bytes = stream.ToArray();
}
Synchrotron answered 10/2, 2023 at 7:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.