How to delete messages from Gmail using python IMAPclient ?

Google does not delete all messages at once according to http://support.google.com/mail/answer/78755?hl=en.
So, first, you have to delete messages in each folder:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from imapclient import IMAPClient

client = IMAPClient('imap.googlemail.com', use_uid=True, ssl=True)
client.login('mymailbox@gmail.com', 'password')

folders = [
    'INBOX',
    '[Gmail]/Drafts',
    '[Gmail]/Important',
    '[Gmail]/Sent Mail',
    '[Gmail]/Spam',
    '[Gmail]/Starred',
]

for f in folders:
    fold = client.select_folder(f)
    res = client.delete_messages(client.search())
    res = client.expunge()
    client.close_folder()

#Google automatically will move deleted messages to "All Mail" folder. 
#Now we can remove all messages from "All Mail"

client.select_folder("[Gmail]/All Mail")
client.set_gmail_labels(client.search(), '\\Trash')
client.delete_messages(client.search())
client.expunge() 
client.logout()

More information on how to work with Gmail using python IMAPClient can be found directly at http://imapclient.freshfoo.com/browser/imapclient/livetest.py
Read the source code, Luke 🙂

How do you count messages in your gmail ?

Here is the short and dirtyeasy way how to:

First we need to install IMAPClient which extends standard module:

sudo pip install IMAPClient

from imapclient import IMAPClient

server = IMAPClient('imap.googlemail.com', use_uid=True, ssl=True)
server.login('mymailbox@gmail.com', 'password')

for f in server.list_folders():
    if f[2] == '[Gmail]':
        continue
    server.select_folder(f[2])
    all = server.search('ALL', None)
    print('%s : %s' % (f[2], len(all)))