pythonwise / imapclean

#!/usr/bin/env python
'''Clean your IMAP inbox

Copy all message to "Archive" and delete them from Inbox
'''

__author__ = "Miki Tebeka <miki@mikitebeka.com>"

from imaplib import IMAP4
import logging as log

def move_messages(server, user, passwd, purge=0):
    imap = IMAP4(server)
    imap.login(user, passwd)
    imap.select()
    messages = imap.search(None, "ALL")[1][0].split()
    for msg_id in messages:
        flags = imap.fetch(msg_id, "(FLAGS)")[1][0]
        if not flags.startswith(msg_id):
            log.error("bad reply for %s flags - %s" % (msg_id, flags))
            continue
        if "Deleted" in flags:
            log.info("skipping %s - already deleted" % msg_id)
            continue
        log.info("deleting %s" % msg_id)
        imap.copy(msg_id, "Archive")
        imap.store(msg_id, "+FLAGS", "\\Deleted")

    if purge:
        log.info("purging deleted messages")
        imap.expunge()
    log.info("logging out")
    imap.close()
    imap.logout()

def main(argv=None):
    if argv is None:
        import sys
        argv = sys.argv

    from optparse import OptionParser
    from getpass import getpass, getuser

    parser = OptionParser("usage: %prog")
    parser.add_option("-p", "--purge", help="purge deleted messages",
        action="store_true", default=0, dest="purge")
    parser.add_option("-v", "--verbose", help="be verbose",
                      dest="verbose", action="store_true", default=0)
    parser.add_option("--server", help="imap server",
            default="localhost", dest="server")
    parser.add_option("--user", help="IMAP user name",
            dest="user", default="")
    parser.add_option("--passwd", help="IMAP password",
            dest="passwd", default="")

    opts, args = parser.parse_args(argv[1:])
    if args:
        parser.error("wrong number of arguments") # Will exit

    level = log.DEBUG if opts.verbose else log.ERROR
    log.basicConfig(format="%(levelname)s: %(message)s",
                        level=level)

    opts.user = opts.user or getuser()
    opts.passwd = opts.passwd or getpass()

    try:
        move_messages(opts.server, opts.user, opts.passwd, opts.purge)
    except Exception, e:
        if opts.verbose:
            log.exception(e)
        else:
            log.error(e)
        raise SystemExit(1)

if __name__ == "__main__":
    main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.