How to access embedded attachments?

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

I use ImapClient to receive emails that may have various attachments (images, text files, binaries, etc.).

The MimeMessage property Attachmenthelps me access all of these attachments --- if emails are not sent from Apple Mail and contain images (it seems that Apple Mail does not attach images with the Content-Disposition "attachment" (read here ... comment from Jeffrey Steadfast at the bottom).

Attached images are not listed in the attachment collection.

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

+4
source share
1 answer

The Messaging document lists several ways to learn the parts of MIME in a message, but another simple option might be to use BodyPartson MimeMessage.

To get started, let's see how the property works MimeMessage.Attachments:

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

As you already noted, the reason this property does not return the attachments you are looking for is because they do not Content-Disposition: attachmenthave what the property checks MimeEntity.IsAttachment.

An alternative rule may be to check the file name parameter.

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

Or maybe you could say that you just want all the images:

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

, , .

+5

All Articles