#!/usr/bin/python
import getpass, imaplib, string, sys

USER = "XXX_YOUR_USERNAME_HERE"
#TRASH = "INBOX.Trash"
TRASH = "Trash"

# This function checks that the return code is OK
# It also prints out what happened (which would end
# up /dev/null'ed in non-verbose mode)
def assertok(res, *args):
    if res != "OK":
        sys.stderr.write("\n%s returned %s - aborting\n" % (`args`,  res ))
        sys.exit(1)

#
# MAIN
#
pw = getpass.getpass()
M = imaplib.IMAP4('localhost')
res, msg = M.login(USER, pw)
assertok(res, 'login', msg)

res, boxes = M.list()
assertok(res, 'list')

for box in boxes:
    print box
    box = string.split(box, '"')[3]
    if box != TRASH:
        res, msg = M.select(box)
        assertok(res, 'select', msg)
        res, deleted = M.uid("SEARCH", "DELETED")
        assertok(res, 'SEARCH')
        if deleted[0] != '':
            for mail in string.split(deleted[0], ' '):
                res, msg = M.uid("COPY", mail, TRASH)
                assertok(res, 'COPY', msg)
        res, msg = M.close()
        assertok(res, 'close', msg)

M.select(TRASH)
res, deleted = M.uid("SEARCH", "DELETED")
assertok(res, 'SEARCH2')
if deleted[0] != '':
    for mail in string.split(deleted[0], ' '):
        res, msg = M.uid("STORE", mail, "-FLAGS.SILENT", "(\\DELETED)")
        assertok(res, "STORE", msg)

M.check()
M.logout()
