Problem deleting emails in gmail using imaplib

Michael Girnyak picture Michael Girnyak · Oct 21, 2010 · Viewed 9.2k times · Source

I try to remove message from inbox folder and all alright, but when i switched to All Mail folder the removing does not work. expunge() method returns ('OK', [None]) and message was not removed:

>>>import imaplib
>>>server = imaplib.IMAP4_SSL('imap.gmail.com','993')
>>>server.login('[email protected]','Password')
>>>server.select('inbox')
>>>for i in server.search(None,'all')[1][0].split():
...    print i+"\n"+server.fetch(i,'(BODY[HEADER.FIELDS (Subject)])')[1][0][1]
...
#  that how i know what UID hame my message? I select by subject
#....
#28
#Subject: 1 Question Has 1 Answer - Stack Overflow
#
#
#29
#Subject: 2222222222
#...
>>>server.store(29,'+FLAGS','\\Deleted')
#('OK', ['29 (FLAGS (\\Seen \\Deleted))'])
>>>server.expunge()
#('OK', ['29'])
>>> server.select('[Gmail]/All Mail')
('OK', ['47'])
>>> for i in server.search(None,'all')[1][0].split():
...  print i+"\n"+server.fetch(i,'(BODY[HEADER.FIELDS (Subject)])')[1][0][1]
... 
#....
#
#46
#Subject: 2222222222
#
#
#47
#Subject: 3333333333333333
#
#....
>>> server.store(47,'+FLAGS','\\Deleted')
('OK', ['47 (FLAGS (\\Seen \\Deleted))'])
>>> server.expunge()
('OK', [None])

Answer

thibault.ketterer picture thibault.ketterer · Apr 19, 2012

it moves all the mail in a given gmail label to the gmail Trash

#!usr/bin/python
import email, imaplib

user = 'xxx'
pwd = 'xxx'

m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)

m.select("some_gmail_label")
m.store("1:*",'+X-GM-LABELS', '\\Trash')

m.expunge() # should be useless, but gmail server says it is ok

Remember to refresh your gmail interface cause it has cache