如何通过 python 和 IMAP 删除超过 2 天的邮件?

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

我有一个脚本可以下载特定 folder/label 的 google 外卖备份导出,完成该部分后,下一步就是执行删除脚本。因为我做的是外卖流程,需要2-3天的时间创建备份才能下载,导致邮件备份比较大。因此,在我等待备份准备好下载的那 2-3 天内,我会收到电子邮件,但这些邮件不会出现在我请求的备份导出中。

所以我希望我的脚本只删除从今天开始 2-3 天后的电子邮件。下面是我的代码,我知道我需要 filter/search 的部分在“ typ, data = mail.search(None, 'ALL') “ 但是,我不确定在哪里可以准确地过滤它并告诉它只发送 flag/select 2-3 天前的电子邮件并发送到垃圾箱。有帮助吗?

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)

这是您代码中的关键行:

typ, data = mail.search(None, 'ALL')

您可以将 ALL 更改为例如BEFORE "12-Oct-2020",因为您实际上并不想搜索所有邮件。有关详细信息和其他可能的搜索关键字,请参阅规范的 pages 49-54 and page 84

顺便说一句,我很惊讶这里有多少问题包含搜索所有邮件的代码。

import datetime
from imap_tools import MailBox, A

with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
    # delete messages older than 2 days from current (INBOX) folder
    mailbox.delete(mailbox.fetch(A(date_lt=datetime.date.today() - datetime.timedelta(days=2))))

https://github.com/ikvk/imap_tools