Question

I am using IMAP4 client called: MailKit. It works great, but I have a problem on getting body of message without downloading the attachments. I want to show the mail's body text and also what attachments there are, but only if a user clicks on the attachment I want to actually download the attachment.

I've tried:

var message = inbox.GetMessage(uid, cancel.Token);

But this gets the entire message.

Also tried:

uids[0] = uid;
var ms = inbox.Fetch(uids, MessageSummaryItems.BodyStructure , cancel.Token);  
var bp1 = inbox.GetBodyPart(uid, ms.First().Body, cancel.Token);

But again this downloads the attachment.

Was it helpful?

Solution

With your sample code, you are downloading the entire message because you are requesting the top-level body part of the message.

MIME is a tree structure of "body parts". What you want to do is to traverse the ms.First().Body to find the part(s) that you want, and then download them individually using the GetBodyPart() method.

Take a look at MailKit.BodyPartMultipart, MailKit.BodyPartMessage, MailKit.BodyPartBasic and MailKit.BodyPartText.

A BodyPartMultipart contains other body parts.

A BodyPartMessage parts contains a message (which will also contain a body part).

A BodyPartBasic is a basic leaf-node body part - usually an "attachment".

A BodyPartText is a text part (a subclass of BodyPartBasic) which can either be an attached text part or what you might consider to be the main text of the message.

To figure out if a BodyPartBasic is meant to be displayed inline or as an attachment, what you need to do is:

if (part.ContentDisposition != null && part.ContentDisposition.IsAttachment)
    // it is an attachment
else
    // it is meant to be shown to the user as part of the message
    // (if it is an image, it is meant to be displayed with the text)

I should probably add a convenience property to BodyPartBasic called IsAttachment to make this a bit simpler (I'll try to add it today).

Hope that helps.

Update: I've just added the BodyPartBasic.IsAttachment convenience property in git master, so the next release of MailKit will have it.

OTHER TIPS

This IMAP command will return just the text body.

     a1 uid fetch <uid> (body.peek[text])

-Rick

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top