Search code examples
python-3.ximapemailimaplib

Message not deleting with m.expunge


I have studied numerous questions and answers here and from what I can see my code is correct. For some reason though, the mail I have selected is not being deleted.

My code is:

m = imaplib.IMAP4_SSL("imap-mail.outlook.com")
m.login("MY_EMAIL","MY_PWORD")
m.select("Sent")
resp, data = m.uid("search", None, "ALL")
uid = data[0].split()[-1]

#Can also get message content with lines 
# resp,data = m.uid('fetch',uid,"(BODY[HEADER])")  
# print(data)

m.store(uid, "+FLAGS", "\\Deleted")                #Works fine to here
m.expunge()                                        #This doesn't delete message
m.close()
m.logout()

If I change the m.expunge() line to print(m.expunge()) I get the tuple

('OK', [None])

The message is still in the mailbox even with the "OK" response. I'm unsure why this happens


Solution

  • You are using UIDs to identify the messages, so you also need to use UID commands to change the \Deleted flag:

    m.uid('STORE' uid, "+FLAGS", "\\Deleted")
    

    You are currently trying to set the deleted flag on Message Sequence Number with the same UID, which probably doesn't exist, or refers to a completely different message.