imap - how to delete messages

Derek picture Derek · Jul 5, 2010 · Viewed 42.3k times · Source

How can I delete messages from the mail box? I am using this code, but the letters are not removed. Sorry for my English.

def getimap(self,server,port,login,password):
    import imaplib, email
    box = imaplib.IMAP4(server,port)
    box.login(login,password)
    box.select()
    box.expunge()
    typ, data = box.search(None, 'ALL')
    for num in data[0].split() :
        typ, data = box.fetch(num, '(UID BODY[TEXT])')
        print num
        print data[0][1]
    box.close()
    box.logout()

Answer

codersofthedark picture codersofthedark · Nov 24, 2011

This is the working code for deleting all emails in your inbox:

import imaplib
box = imaplib.IMAP4_SSL('imap.mail.microsoftonline.com', 993)
box.login("[email protected]","paswword")
box.select('Inbox')
typ, data = box.search(None, 'ALL')
for num in data[0].split():
   box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
box.logout()