How to access embedded attachments?
Asked Answered
K

1

6

I am using MailKit/MimeKit 1.2.7 (latest NuGet version).

I am using ImapClient to receive emails that can have diverse attachments (images, text files, binary files, etc).

MimeMessage's Attachment property helps me access all these attachments --- unless the emails are being sent with Apple Mail and contain images (it seems that Apple Mail does not attach images with Content-Disposition "attachment" (read here ... comment from Jeffrey Stedfast at the very bottom).

Embedded images are not listed in the Attachments collection.

What are my options? Do I really have to traverse the body parts one by one and see what's inside? Or is there an easier solution?

Ka answered 15/7, 2015 at 7:15 Comment(2)
Please see "Should questions include “tags” in their titles?", where the consensus is "no, they should not"!Travesty
Oops. Sorry about that. Won't happen again.Ka
S
9

The Working with Messages document lists a few ways of examining the MIME parts within a message, but another simple option might be to use the BodyParts property on the MimeMessage.

To start, let's take a look at how the MimeMessage.Attachments property works:

public IEnumerable<MimeEntity> Attachments {
    get { return BodyParts.Where (x => x.IsAttachment); }
}

As you've already noted, the reason that this property doesn't return the attachments you are looking for is because they do not have Content-Disposition: attachment which is what the MimeEntity.IsAttachment property is checking for.

An alternate rule might be to check for a filename parameter.

var attachments = message.BodyParts.Where (x => x.ContentDisposition != null && x.ContentDisposition.FileName != null).ToList ();

Or maybe you could say you just want all images:

var images = message.BodyParts.OfType<MimePart> ().Where (x => x.ContentType.IsMimeType ("image", "*")).ToList ();

Hope that gives you some ideas on how to get the items you want.

Serpentiform answered 15/7, 2015 at 14:47 Comment(2)
Yes, both code snippet worked perfectly for me. In fact I need both (first find all attachments and second give some special treatment to the images). Thank you, Jeffrey! This helped a lot!!Ka
Warning: inline images might still have no content-disposition set. Don't use the 2nd snippet of the answerMarya

© 2022 - 2024 — McMap. All rights reserved.