How to delete messages from Gmail using python IMAPclient ?

Google does not delete all messages at once according to
So, first, you have to delete messages in each folder:

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

from imapclient import IMAPClient

client = IMAPClient('', use_uid=True, ssl=True)
client.login('', 'password')

folders = [
    '[Gmail]/Sent Mail',

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

#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(, '\\Trash')

More information on how to work with Gmail using python IMAPClient can be found directly at
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('', use_uid=True, ssl=True)
server.login('', 'password')

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