6

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));
  }
Ran Lorch
  • 73
  • 8
  • Possible duplicate of [Mimekit, IMapClient get attachment information without downloading whole message](https://stackoverflow.com/questions/36881966/mimekit-imapclient-get-attachment-information-without-downloading-whole-message) – Gonzo345 Dec 17 '18 at 09:45
  • i'll try this thank you – Ran Lorch Dec 18 '18 at 03:13

1 Answers1

6

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
jstedfast
  • 35,744
  • 5
  • 97
  • 110