imap deleting messages

2019-03-15 07:31发布

问题:

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()

回答1:

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()


回答2:

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("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()


回答3:

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

import imaplib
from email.parser import HeaderParser
m = imaplib.IMAP4_SSL("your_imap_server")
m.login("your_username","your_password")
# get list of mailboxes
list = m.list()
# select which mail box to process
m.select("Inbox") 
resp, data = m.uid('search',None, "ALL") # search and return Uids
uids = 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 mailbox
m.logout() # logout 


回答4:

If you are using GMail the process is a bit different:

  1. Move it to the [Gmail]/Trash folder.
  2. Delete it from the [Gmail]/Trash folder (Add \Delete flag)

All emails in [Gmail]/Spam and [Gmail]/Trash are deleted after 30 days. If you delete a message from [Gmail]/Spam or [Gmail]/Trash, it will be deleted permanently.

Remember also to call EXPUNGE after setting the tag Deleted.



回答5:

This is what works for me, and it is really fast as I don't delete each email individually (store) but pass the list index instead. This works for gmail personal as well as enterprise (Google Apps for Business). It first selects the folder/label to use m.list() will show you all available. It then searches for emails over a year old, and performs a move to trash. It then flags all the emails in trash with the delete flag and expunges everything:

#!/bin/python

import datetime
import imaplib

m = imaplib.IMAP4_SSL("imap.gmail.com")  # server to connect to
print "Connecting to mailbox..."
m.login('gmail@your_gmail.com', 'your_password')

print m.select('[Gmail]/All Mail')  # required to perform search, m.list() for all lables, '[Gmail]/Sent Mail'
before_date = (datetime.date.today() - datetime.timedelta(365)).strftime("%d-%b-%Y")  # date string, 04-Jan-2013
typ, data = m.search(None, '(BEFORE {0})'.format(before_date))  # search pointer for msgs before before_date

if data != ['']:  # if not empty list means messages exist
    no_msgs = data[0].split()[-1]  # last msg id in the list
    print "To be removed:\t", no_msgs, "messages found with date before", before_date
    m.store("1:{0}".format(no_msgs), '+X-GM-LABELS', '\\Trash')  # move to trash
    print "Deleted {0} messages. Closing connection & logging out.".format(no_msgs)
else:
    print "Nothing to remove."

#This block empties trash, remove if you want to keep, Gmail auto purges trash after 30 days.
print("Emptying Trash & Expunge...")
m.select('[Gmail]/Trash')  # select all trash
m.store("1:*", '+FLAGS', '\\Deleted')  #Flag all Trash as Deleted
m.expunge()  # not need if auto-expunge enabled

print("Done. Closing connection & logging out.")
m.close()
m.logout()
print "All Done."


标签: python imap