mojo1012
mojo1012

Reputation: 19

My Python code runs but doesn't delete selected email from Gmail Inbox

My Python code below runs but doesn't delete selected emails that I'm expecting to be deleted from my test gamil\inbox. I'm not sure what am I doing wrong here. I will really appreciate any help.

import imaplib
import datetime


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('[email protected]', 'gmail_pass')
 
print("{0} Searching Inbox by sender...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
m.select('Inbox') #select folder to search
status, messages = m.search(None, 'FROM "[email protected]"') # search for specific mails by sender

print("{0} Flagging selected mail as deleted...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
for mail in messages[0].split():
    m.store(mail, "+FLAGS", "\\Deleted")
    m.expunge()
        
print("{0} Done. Closing connection & logging out.".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
m.close()
m.logout()

Upvotes: 0

Views: 346

Answers (2)

mojo1012
mojo1012

Reputation: 19

Thanks a lot Max! Your answer helped me fixing my problem. However, if I use "\Deleted" then I see messages are removed from the inbox but still available in "All Mail" folder. Does this mean they are permanently deleted? So I tried using as below with moving to "Trash" now messages are removed from the inbox but moved to "Trash".

for mail in messages[0].split():
    #m.store(mail, "+FLAGS", "\\Deleted")
    m.store(mail, '+X-GM-LABELS', '\\Trash')
m.expunge()

Upvotes: 0

Max
Max

Reputation: 11000

Do not run expunge until you are out of the for loop. expunge renumbers the message ids, so the numbers you have from your search do not correspond anymore.

So:

for mail in messages[0].split():
    m.store(mail, "+FLAGS", "\\Deleted")
m.expunge()

This is one of the reasons why it is a separate operation. Or use UIDs everywhere.

Also, on gmail, deleting does not actually delete messages. It only marks it as removed from that Label (inbox). If you want to actually delete it, you need to move it to the Trash folder, then delete it from there.

Upvotes: 1

Related Questions