Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access embedded attachments?

Tags:

c#

mimekit

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?

like image 932
Ingmar Avatar asked Jul 15 '15 07:07

Ingmar


1 Answers

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.

like image 98
jstedfast Avatar answered Sep 19 '22 14:09

jstedfast