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 http://wiki.dovecot.org/HowTo/RefilterMail , I wrote this Python script:

#!/usr/bin/python
import imaplib, re, os

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

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

dst = None
if re.search('To: .*@student.dtu.dk', headers): dst = 'Archives.2010.DTU'
if re.search('Subject: .*\[somelist\]', headers): dst = 'Archives.2010.Somelist'
if dst == None: dst = 'Archives.2010'

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

server.expunge()
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')

No comments:

Post a Comment