Ran Lorch
Ran Lorch

Reputation: 73

filter email with attachment using mimekit/mailkit

is there a way to filter emails with attachments only? I'm using this code

using (var client = new ImapClient())
       {
         client.Connect(IMAPServer, IMAPport, IMAPSSL);
         client.AuthenticationMechanisms.Remove("XOAUTH2");
         client.Authenticate(User, Password);
         var inbox = client.Inbox;
         inbox.Open(FolderAccess.ReadOnly);
         //filter email with attachments only
           var results = inbox.Search(SearchQuery.NotSeen.And(SearchQuery.NotDeleted));
  }

Upvotes: 6

Views: 2209

Answers (1)

jstedfast
jstedfast

Reputation: 38643

Unfortunately, IMAP does not provide a search query term for checking if a message has an attachment, but what you can do is construct a search query with the other criteria that you want (much like you have already done), and then do:

var results = inbox.Search(SearchQuery.NotSeen.And(SearchQuery.NotDeleted));
var items = MessageSummaryItems.BodyStructure | MessageSummaryItems.UniqueId;
var matched = new UniqueIdSet ();

foreach (var message in inbox.Fetch (results, items)) {
    if (message.BodyParts.Any (x => x.IsAttachment))
        matched.Add (message.UniqueId);
}

// `matched` now contains a list of UIDs of the messages that have attachments
// and also fit your other search criteria

Upvotes: 6

Related Questions