Web Dev Ramblings

MailKit Attachments

Published Friday, August 12, 2016

Today I found myself trying to download attachments from a mail message I'd downloaded with MailKit from an IMAP account. When it comes down to it this was incredibly easy. But finding out how to do it was not.

Since Google is your friend I did the obvious and tried to search for a solution. I wound up on the proper MailKit site and got to some article which didn't really manage to tell me how to do it. Second I got this little gem which had some hints but was written in barely understandable English. So with the hopes of helping at least one other person not suffer through this, this is how to do it:

MimeMessage mimeMessage = GetSomeMessage(); foreach (MimePart mp in mimeMessage.Attachments) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); mp.ContentObject.DecodeTo(ms); }

And that's all you need to get the raw bytes. What I missed in my first attempt was that mimeMessage.Attachments here actually isn't of type MimePart but rather is a collection of MimeEntity which do not have the ContentObject property which you need in order to get to the actual data.

What you do next ofc depends on what type of attachment it is, for my specific use case I was looking for a .ics file:

if (entity.ContentType.MimeType == "application/ics") { String ics = System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()); // do something with the ics file contents }
Or maybe write it to disk:
System.IO.File.WriteAllBytes(someLocalPath + mp.FileName, ms.ToArray());