Search code examples
pythongmailimap

How to delete emails older than 2 days through python and IMAP?


I have a script that would download the google takeout backup export of a particular folder/label, once that part is done, the next step is to execute the delete script. Because I do the takeout process, it takes 2-3 days to create the back up before I can download it, cause the email backup is quite large. So during that 2-3 days while I wait for the backup to be ready to download, I'll be getting emails and those won't be in the backup export that I've requested.

So I want my script to just delete emails 2-3 days from today's date. Below is my code and I know the section I need to filter/search is in " typ, data = mail.search(None, 'ALL') " However, I'm unsure where to exactly filter this and tell it to only flag/select emails that are 2-3 days old and sent to trash. Any help?

def deleteEmailIMAP(user, password, IMAP):
        mail = imaplib.IMAP4_SSL(IMAP)
        mail.login(user, password)
        print("Logging into account:", email )
        mail.select("Process") #select folder/label
        print("Process Folder Selected")
        time.sleep(2)
        typ, data = mail.search(None, 'ALL')
        print(" Emails from Process Folder sent to Trash")
        for num in data[0].split():
            mail.store(num, '+X-GM-LABELS', r'(\Trash)') #sent to trash and removed from folder
        mail.expunge()
        print("Sent to Trash.")
        print("Emptying Trash & Expunge...")
        mail.select('[Gmail]/Trash')  # select all trash
        mail.store("1:*", '+FLAGS', '\\Deleted')  #Flag all Trash as Deleted
        mail.expunge()  # not need if auto-expunge enabled
        print("Done. Closing connection & logging out.")
        time.sleep(2)
        mail.close()
        mail.logout()
        exit()
    deleteEmailIMAP(email, passw, imapserver)

Solution

  • import datetime
    from imap_tools import MailBox, A
    
    with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
        # delete messages older than 2 days from current (INBOX) folder
        mailbox.delete(mailbox.uids(A(date_lt=datetime.date.today() - datetime.timedelta(days=2))))
    

    https://github.com/ikvk/imap_tools