Mimekit, IMapClient get attachment information wit

2019-09-10 07:26发布

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条回答
Explosion°爆炸
2楼-- · 2019-09-10 07:32

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.

查看更多
登录 后发表回答