Sunday, February 28, 2010

Automatic archiving of IMAP mailbox

I was looking for a way to let my IMAP server automatically move old mail to the correct IMAP folder based on a given specification. I wanted to simply drag mail that I wanted archived to a IMAP folder called Archives, and then let the server put it in the correct subfolder itself. Inspired by , I wrote this Python script:

import imaplib, re, os

server = imaplib.IMAP4('localhost')
server.login('username', 'password')
r ='Archives')
resp, items =, 'ALL')

for m in items[0].split():
resp, data = server.fetch(m, '(BODY[HEADER.FIELDS (SUBJECT FROM TO)])')
_, headers = data[0]

dst = None
if'To: .*', headers): dst = 'Archives.2010.DTU'
if'Subject: .*\[somelist\]', headers): dst = 'Archives.2010.Somelist'
if dst == None: dst = 'Archives.2010'

resp, data = server.copy(m, dst)
if resp == 'OK':, '+Flags', '\\Deleted')

You can obscure the password by using base64.b64decode to prevent people seeing you password when looking over your shoulder.

To make the script run automatically every time a mail is dropped to the Archives folder, use incron. Type incrontab -e and write the following line
/home/username/Maildir/.Archives/cur/ IN_MOVED_TO,IN_ONESHOT python /path/to/script
Where /path/to/script here is the path of the above Python script.

Also, if you want to use this automatic triggering, add the following line to the end of the Python script
os.system('incrontab --reload')