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);
}
Yes, this is possible. In order to do this, however, you'll need to pass the
MessageSummaryItems.BodyStructure
flag to theFetch()
method.This will populate the
summary.Body
property.If the
Body
property is populated, you can use theBodyParts
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:One way to check for xls/xlsx attachments might be the following:
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:
...and probably other places.