14

Can you delete emails with imaplib? If so how?

Demon Labs
  • 339
  • 2
  • 6
  • 15
  • 2
    as of mid-2012 none of the answers below work unless you first adjust the default imap settings -- see http://stackoverflow.com/questions/3988583/problem-deleting-emails-in-gmail-using-imaplib – GJ. Jun 25 '12 at 19:05

3 Answers3

22

Use the store method (of the IMAP4 object representing your connection) to set the r'\Deleted' flag on the message number you want to delete, as the example in the docs show; then the expunge method to actually perform all deletions so marked.

Gmail's implementation of IMAP has subtly different semantics, by default, but if you want you can tweak it to behave much more like a traditional IMAP implementation (where the above sequence works) -- basically you have to enable the "Advanced IMAP Controls" lab, then follow the instructions at the URL I gave to get exactly the IMAP semantics you desire (physically deleting rather than archiving "deleted" mails, waiting or not for expunge, and so forth).

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
19

Deleting an email over IMAP is performed in two phases:

  • mark one or more items for deletion: imap.store(msg_no, '+FLAGS', '\\Deleted')
  • expunge the mailbox: imap.expunge()

(imap is your IMAP4 object)

SimonJ
  • 21,076
  • 1
  • 35
  • 50
  • This is removing my email from my inbox. But if I search gmail for the item it is still there. Any idea? Using this specifically with gmail. Any difference depending on python version or gmail settings? – Dan Ciborowski - MSFT Mar 19 '13 at 14:57
  • It'll move the email to your Bin label, which is cleaned up automatically every 30 days. – hd1 Jun 01 '13 at 18:47
11
imap.uid('STORE', list_of_msgno , '+FLAGS', '(\Deleted)')  
imap.expunge() 

i.e

imap.uid('STORE', '2, 4, 9, 12' , '+FLAGS', '(\Deleted)') 

Here (2, 4, 9, 12) are uid of the messages which are going to be deleted.

Nobilis
  • 7,310
  • 1
  • 33
  • 67
Avadhesh
  • 4,519
  • 5
  • 33
  • 44