When dealing with message folder, the temptation is strong to re-invent the wheel when it comes to make a search through its messages. One evident solution is to grab all the messages, test against the criteria, and if the message matches, store it for further need.

Since JavaMail 1.1, a search facility has been provided. It is located in the jaxax.mail.search package. To make a complex search, you just create the needed search terms and compose them with a AND or OR operator. The next step is to call the magic method on the message folder : Folder.search(SearchTerm term) that returns an array of Message instance.

It may be look weird to add such complexity to a simple search in a mail folder, but when it comes to term composition, this solution is the most flexible and above all, when you look at your code, the nicest one.