Today I was looking for a way to execute complex queries in Apple’s Mail to create a “smart mailbox”.
You may already know that Mail has some of the power of Spotlight’s search syntax. You can read about some of the details of searching in Mail at the excellent Hawkwings blog. Basically you create a query in the search box in Mail. Once you have your query getting the results you want, you click on the “Save” button to create a smart mailbox with that search. Its just like creating a saved search folder in the finder.
You can take your queries a step further and combine the power of Spotlight syntax with search items that are only available in Mail such as limiting the mailbox that the message is in. The magic is using Spotlight queries inside the smart mailbox dialog.
Let’s use a simple example. Say that I want to create a smart mailbox that has all the mail either from or to a particular person and is in the inbox. So the logic would look something like this: ((from:aperson OR to:aperson) AND in:inbox) With the standard functionality in smart mailboxes or in Mail’s search box, this query is not possible. But Mail can combine both the spotlight syntax and the smart mailbox filters to allow us to create complex queries that combine both.
To use the Spotlight search syntax, select “Entire Message” then “Contains”. In the box following, enter your Spotlight search query. In this example I used “from:mikel OR to:mikel” which would find all messages where mikel was either the sender or a recipient. Then I wanted to ensure that only messages from the Inbox were returned, not any of the other IMAP folders. So I used a Mail only feature to limit the search to the Inbox and set the search to match ALL conditions.
So what happens is that first the Spotlight query is run, returning all messages from or to mikel. Then those messages are filtered leaving only those that are in the Inbox. Pretty cool.