How can I use SearchTerm to match specific messages with POP/IMAP servers?

Andrea Pompili

You have to build a condition tree using the single SearchTerm blocks given in the JM API (package javax.mail.search.*).
The SearchTerm blocks are of this type:

  • AND terms (class AndTerm)
  • OR terms (class OrTerm)
  • NOT terms (class NotTerm)
  • SENT DATE terms (class SentDateTerm)
  • CONTENT terms (class BodyTerm)
  • HEADER terms (From, Recipients, Subjects, etc..) (classes FromStringTerm, RecipientStringTerm, SubjectTerm)
Once you have built the searching term using these blocks, you have to use this method:
foldername.search(search term);
For example, to search in the INBOX folder all messages with body and subject containing the word "hello" you have to write that:
//Initialize the folder and the search term
Folder folder = store.getFolder("INBOX");
SearchTerm st = new AndTerm(
   new SubjectTerm("hello"), 
   new BodyTerm("hello"));

Message[] msgs = folder.search(st);
Now you have an array of messages that match your request.
This code doesn't depend on the protocol used and is the same in POP3, IMAP, or other existing protocol.

If you want you can write your own search term extending one of these classes and writing inside your own searching logic.