imap - how to delete messages imap - how to delete messages python python

imap - how to delete messages


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

import imaplibbox = imaplib.IMAP4_SSL('imap.mail.microsoftonline.com', 993)box.login("user@domain.com","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()


I think you should mark the emails to be deleted, first.. For example:

for num in data[0].split():   box.store(num, '+FLAGS', '\\Deleted')box.expunge()


The following code prints some message header fields and then delete message.

import imaplibfrom email.parser import HeaderParserm = imaplib.IMAP4_SSL("your_imap_server")m.login("your_username","your_password")# get list of mailboxeslist = m.list()# select which mail box to processm.select("Inbox") resp, data = m.uid('search',None, "ALL") # search and return Uidsuids = data[0].split()    mailparser = HeaderParser()for uid in uids:    resp,data = m.uid('fetch',uid,"(BODY[HEADER])")            msg = mailparser.parsestr(data[0][1])           print (msg['From'],msg['Date'],msg['Subject'])            print m.uid('STORE',uid, '+FLAGS', '(\\Deleted)')print m.expunge()m.close() # close the mailboxm.logout() # logout