Gmail Delete Old Emails using Python

The last few weeks I had some time to play with pythons imaplib. I came up with this script that cleans up your inbox. It works for personal as well as google apps enterprise/ business accounts. Tinker with it a bit and its usable for any IMAP accessible email:

def connect_imap():
    m = imaplib.IMAP4_SSL("imap.gmail.com")  # server to connect to
    print("{0} Connecting to mailbox via IMAP...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
    m.login('you@gmail.com', 'your_pass!')

    return m

def move_to_trash_before_date(m, folder, days_before):
    no_of_msgs = int(m.select(folder)[1][0])  # required to perform search, m.list() for all lables, '[Gmail]/Sent Mail'
    print("- Found a total of {1} messages in '{0}'.".format(folder, no_of_msgs))

    before_date = (datetime.date.today() - datetime.timedelta(days_before)).strftime("%d-%b-%Y")  # date string, 04-Jan-2013
    typ, data = m.search(None, '(BEFORE {0})'.format(before_date))  # search pointer for msgs before before_date

    if data != ['']:  # if not empty list means messages exist
        no_msgs_del = data[0].split()[-1]  # last msg id in the list
        print("- Marked {0} messages for removal with dates before {1} in '{2}'.".format(no_msgs_del, before_date, folder))
        m.store("1:{0}".format(no_msgs_del), '+X-GM-LABELS', '\\Trash')  # move to trash
        #print("Deleted {0} messages.".format(no_msgs_del))
        print("- Nothing to remove.")


def empty_folder(m, folder, do_expunge=True):
    print("- Empty '{0}' & Expunge all mail...".format(folder))
    m.select(folder)  # select all trash
    m.store("1:*", '+FLAGS', '\\Deleted')  # Flag all Trash as Deleted
    if do_expunge:  # See Gmail Settings -> Forwarding and POP/IMAP -> Auto-Expunge
        m.expunge()  # not need if auto-expunge enabled
        print("Expunge was skipped.")

def disconnect_imap(m):
    print("{0} Done. Closing connection & logging out.".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
    #print "All Done."

if __name__ == '__main__':

    m_con = connect_imap()

    move_to_trash_before_date(m_con, '[Gmail]/All Mail', 365)  # inbox cleanup, before 1 yr

    move_to_trash_before_date(m_con, '[Gmail]/Sent Mail', 31)  # sent cleanup, before 1 mth

    empty_folder(m_con, '[Gmail]/Trash', do_expunge=True)  # can send do_expunge=False, default True


Any suggestions to make this even faster are welcome. It was already optimized quite a bit, I found samples that did a for loop and store individually on each message.

Current rating: 5