pythonwise / imapclean

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

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

__author__ = "Miki Tebeka <>"

from imaplib import IMAP4
import logging as log

def move_messages(server, user, passwd, purge=0):
    imap = IMAP4(server)
    imap.login(user, passwd)
    messages =, "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))
        if "Deleted" in flags:
  "skipping %s - already deleted" % msg_id)
            continue"deleting %s" % msg_id)
        imap.copy(msg_id, "Archive"), "+FLAGS", "\\Deleted")

    if purge:"purging deleted messages")
        imap.expunge()"logging out")

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",

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

        move_messages(opts.server, opts.user, opts.passwd, opts.purge)
    except Exception, e:
        if opts.verbose:
        raise SystemExit(1)

if __name__ == "__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
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.