Mimekit, IMapClient get attachment information without downloading whole message

给你一囗甜甜゛ 提交于 2019-12-12 01:28:46

问题


I am using the following code to obtain subject information.

Is it possible to know if the email contains attachments, and perhaps more specifically excel spreadsheets (xls/xlsx) without downloading the entire message?

client.Connect("imap.gmail.com", 993);
client.Authenticate("spyperson", "secret-word");
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadOnly);

Console.WriteLine("Total messages: {0}", inbox.Count);
Console.WriteLine("Recent messages: {0}", inbox.Recent);

var uids = inbox.Search(SearchQuery.NotSeen);
foreach (var summary in inbox.Fetch(uids, MessageSummaryItems.Full | MessageSummaryItems.UniqueId | MessageSummaryItems.Flags))
{
    Console.WriteLine("[summary] {0:D2}: {1}:{2}", summary.Index, summary.Envelope.Subject, summary.Flags);
}

回答1:


Yes, this is possible. In order to do this, however, you'll need to pass the MessageSummaryItems.BodyStructure flag to the Fetch() method.

This will populate the summary.Body property.

If the Body property is populated, you can use the BodyParts property as a quick & dirty way of iterating over a flattened hierarchy of body parts in the message, checking if any of them are attachments like this:

var hasAttachments = summary.BodyParts.Any (x => x.IsAttachment);

One way to check for xls/xlsx attachments might be the following:

var hasAttachments = summary.BodyParts.Any (x => x.IsAttachment &&
    x.FileName != null && (x.FileName.EndsWith (".xls") ||
    x.FileName.EndsWith (".xslsx")));

These are very simplistic checks, however, and most likely your interpretation of what is or isn't an attachment will conflict with what the IsAttachment property tells you, so I'd probably recommend using either the Visitor pattern for traversing the MIME hierarchy or else using recursion and using your own logic to determine if a part is an attachment by your own custom definition (everyone seems to have their own unique interpretation of what constitutes an "attachment" when it comes to email).

I've got docs on common MIME hierarchies in the following locations:

  1. http://www.mimekit.net/docs/html/WorkingWithMessages.htm#MessageStructure
  2. http://www.mimekit.net/docs/html/FrequentlyAskedQuestions.htm#MessageBody

...and probably other places.



来源:https://stackoverflow.com/questions/36881966/mimekit-imapclient-get-attachment-information-without-downloading-whole-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!