eightShirt eightShirt - 16 days ago 5
Python Question

How to delete most recently mail sent in python?

Using python and

imaplib
, how can I delete the most recently sent mail?
I have this:

mail = imaplib.IMAP4_SSL('imap-mail.outlook.com')
mail.login('MYEMAIL@hotmail.com', 'MYPASS')
mail.select('Sent')
mail.search(None, "ALL") # Returns ('OK', ['1 2 ... N'])
# doubt


Thanks in advance!

Answer

I found a solution that worked for me. After get sent mailbox access I was needing to found a message with fetch() function and then delete the email message with expunge() function. From imaplib documentation:

IMAP4.expunge()

Permanently remove deleted items from selected mailbox. Generates an EXPUNGE response for each deleted message. Returned data contains a list of EXPUNGE message numbers in order received.

My code:

mail = imaplib.IMAP4_SSL('imap-mail.outlook.com')
mail.login('MYEMAIL@hotmail.com', 'MYPASS')
mail.select('Sent')

typ, data = mail.search(None, 'ALL')
control = 0
tam = len(data[0].split())
while control < tam:
    typ, data = mail.fetch(tam - control, '(RFC822)')
    if str(data).find(msg['Subject']) and str(data).find(msg['To']) != -1:
        print "Msg found! ", control + 1, "most recently message!"
        mail.store(str(tam - control), '+FLAGS', '\\Deleted')
        mail.expunge()
        break
    control = control + 1

mail.close()
mail.logout()
Comments