IMAP Search Musings

I think most geeks get a ton of email. I’ve been rather selective in what lists I join (and what mail I just auto-delete at the server level), so I only get perhaps a couple hundred emails a day now.

For various ridiculous reasons, searching a mailbox is hard. Most of my mail clients will do it, but sometimes I really want to do it myself because I want to be more exacting. Lately I’ve been tinkering more and more with using IMAP from the command line. Partially it’s that IMAP is really just a little bit unusual and kind of intriguing. But mostly, it’s just that, from time to time, it’s easier for me to just send some manual IMAP commands if I know what I’m doing. (For example, I have absolutely no idea how to subscribe to a particular folder in any of the mail clients I have available. I could wade through the menus and maybe find it, but it’s easier for me to just use Net::IMAP to subscribe to the folder.)

Like most implementations, Ruby’s Net::IMAP library provides a search method. And, like most implementations, it does a very poor job of documenting what is supported. At the risk of sounding like I’ve lost my mind, I actually found the IMAP RFC (3501) to be the easiest bit of documentation to understand. Below are some examples:

You can chain keys, so the following is a valid search command:

FROM "matt" SUBJECT "bacon"

But what isn’t abundantly clear is that search terms are combined with a logical AND, so the above will only match mail from Matt with “bacon” in the subject line.

This appears to be the way to get a logical OR instead:

(FROM "matt") OR (SUBJECT "bacon")

After spending a while trying to get all possible keys for a text search — e.g., (FROM "foo") OR (SUBJECT "foo") OR (CC "foo")... — I realized that there’s an easier way: the TEXT key, which searches headers and the body. So for my generic search method, the search simply became TEXT "foo".

You may also find some of the other keys interesting, like the ability to search for RECENT or FLAGGED. I don’t intend to provide an exhaustive list here, however.

Leave a Reply

Your email address will not be published. Required fields are marked *