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 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *


*