简体   繁体   中英

How to check if message has attachments (MailKit)

I'm using IMAP4 client called: MailKit.

It works great, but I have a problem knowing whether the message has attachments or not.

I've tried:

var summary = inbox.Fetch(MessageId,MessageSummaryItems.Body,cancel.Token).FirstOrDefault();  
var bodyMultiPart = summary.Body as BodyPartMultipart;
if (bodyMultiPart != null)
{
   foreach (var bodyPart in bodyMultiPart.BodyParts.Where(x => x is BodyPartBasic))
   {
        BodyPartBasic basicPart = bodyPart as BodyPartBasic;
        if (basicPart.ContentDisposition != null && basicPart.ContentDisposition.IsAttachment)
        {
           //add basic part as attachment
        }               
   }    
}

But for some messages (for example: message that has PDF as attachment) the content disposition is null .

Try using MessageSummaryItems.BodyStructure instead of MessageSummaryItems.Body.

BODYSTRUCTURE retrieves more details for each body part than BODY does. I think that the Content-Disposition header is one of the extra things that BODYSTRUCTURE retrieves over plain BODY.

Hope that helps.

When the content disposition is null, you can use the content type as a hint: text/* is seldom an attachment, multipart/* is not a hint, other types generally hint at attachments.

PDF is application/pdf, so that's an attachment according to this heuristic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM