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?

Community
  • 1
  • 1
Ingmar
  • 1,525
  • 6
  • 34
  • 51
  • Please see ["Should questions include “tags” in their titles?"](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles), where the consensus is "no, they should not"! –  Jul 15 '15 at 14:53
  • Oops. Sorry about that. Won't happen again. – Ingmar Jul 15 '15 at 18:34

1 Answers1

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.

jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • 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!! – Ingmar Jul 15 '15 at 18:35
  • Warning: inline images might still have no content-disposition set. Don't use the 2nd snippet of the answer – Alex from Jitbit Mar 10 '21 at 11:05