Search code examples
pythonimap

How to delete only one, specific message using IMAP in Python


I'm looking for one, specific message, and then, after found, I want to delete it from inbox. Just this one. My code:

import email
import imaplib

def check_email(self, user, password, imap, port, message):
    M = imaplib.IMAP4_SSL(imap, port)
    M.login(user, password)
    M.select()
    type, message_numbers = M.search(None, '(ALL)')

    subjects = []

    for num in message_numbers[0].split():
        type, data = M.fetch(num, '(RFC822)')
        msg = email.message_from_bytes(data[0][1])
        subjects.append(msg['Subject'])

    if message in subjects:
        M.store(num, '+FLAGS', '\\Deleted')
    else:
        raise FileNotFoundError('Ooops!')

    M.close()
    M.logout()

I want to find and delete only one mail by title, gven in the variable (message). Can you help me?


Solution

  • You loop over all the messages, then delete the last one (which is what num ends up pointing to after the loop finishes) if any one of the messages has a subject which matches. You probably want to reindent the code so that the check takes place inside the loop, and probably abandon the rest of the loop once you found the one you want.

    def check_email(self, user, password, imap, port, message):
        M = imaplib.IMAP4_SSL(imap, port)
        M.login(user, password)
        M.select()
        type, message_numbers = M.search(None, '(ALL)')
    
        found = False
    
        for num in message_numbers[0].split():
            type, data = M.fetch(num, '(RFC822)')
            msg = email.message_from_bytes(data[0][1])
            # No need to collect all the subjects in a list
            # Just examine the current one, then forget this message if it doesn't match
            if message in msg['Subject']:
                M.store(num, '+FLAGS', '\\Deleted')
                found = True
                break
    
        # Don't raise an exception before cleaning up
        M.close()
        M.logout()
    
        # Now finally
        if not Found:
            raise FileNotFoundError('Ooops!')