Filtering your IMAP mailbox from a client-side filter

By | 3rd February 2019

With an increasing amount of email, I’ve found myself using query after query, often in the middle of conference calls, to find the information I need. Not the best situation, so I wanted to filter my email for specific senders into a dedicated folder on my mail provider.

Many moons ago I used to run fetchmail on a Linux host to pull email from a remote server. This time I didn’t want that complexity.

My email provider only provides filtering in their hosted spam filter, into a predefined Spam folder. Unfortunately any rules set in their webmail client do not operate server-side, as one might (naively) hope.

So I’ve settled on imapfilter for the time being. This a brief run through of getting this up and running on your kit.

First off, install the package:

# apt-get install imapfilter

Then in your standard user account, create the configuration file:

$ mkdir ~/.imapfilter && touch ~/.imapfilter/config.lua && pico -$ ~/.imapfilter/config.lua

Paste in this sample config (written in LUA), updating as indicated (square brackets):

options.subscribe = true
options.expunge = true
options.create = true
accountA = IMAP {
  server = "[server name here]",
  username = "[your user name here]",
  password = "[mailbox password here]",
  ssl = "tls1.2"
messages = accountA["INBOX"]:contain_from("")

The last two lines operate the search and move functions. It is sensible to enforce TLS 1.2. This tool appears to handle certificates correctly.

Test it out:

$ imapfilter

You will get some standard output if it is working as expected. The last two lines should be duplicated (not great) for each filter rule, but there are some examples on the web of tiding this up.

If it works correctly (use some test data to start), then it is time to automate.

$ mdkir ~/bin; pico -$ ~/bin/mailmover

Copy the following into the script:

cd ~/.imapfilter
imapfilter &> /dev/null

This is not strictly neccessary but is my preferred approach. Then add the entry to the user crontab:

$ crontab -e


*/10 * * * * /home/[username]/bin/mailmover

This runs the script every ten minutes. And that’s it.

NB: I’m technically incorrect in my use of the term “mailbox” in this blog post. In the IMAP specification (RFC 3501), what we might think of as “folders” within a mailbox are termed “mailboxes” (in the terminology of the RFC, “remote message folders”).

NNB: The imapfilter manpage suggests using the string “auto” for the ssl directive, on the grounds that OpenSSL has discouraged the use of version-specific settings. If you’re willing to put the effort to maintain this parameter, I can see a strong advantage in doing precisely the opposite: explicitly specify the SSL/TLS version. If you’re keen to follow the manpage however, set this to “auto”.

This site uses Akismet to reduce spam. Learn how your comment data is processed.