[英]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.因为我是做外卖的,所以需要2-3天的时间来创建备份,然后才能下载,因为电子邮件备份很大。 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.因此,在我等待备份准备好下载的那 2-3 天内,我会收到电子邮件,而这些电子邮件不会出现在我请求的备份导出中。
So I want my script to just delete emails 2-3 days from today's date.所以我希望我的脚本从今天的日期起 2-3 天删除电子邮件。 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.下面是我的代码,我知道我需要过滤/搜索的部分在“ typ, data = mail.search(None, 'ALL') ” 但是,我不确定在哪里准确过滤它并告诉它只标记/选择 2-3 天前并发送到垃圾箱的电子邮件。 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)
This is the key line from your code:这是您的代码中的关键行:
typ, data = mail.search(None, 'ALL')
You can change the ALL
to eg BEFORE "12-Oct-2020"
, because you don't actually want to search for all mail.您可以将ALL
更改为例如BEFORE "12-Oct-2020"
,因为您实际上并不想搜索所有邮件。 See pages 49-54 and page 84 of the specification for details and other possible search keys.有关详细信息和其他可能的搜索关键字,请参见规范的第 49-54 页和第 84 页。
As an aside, I am quite amazed by how many questions here contain code to search for all mail.顺便说一句,我很惊讶这里有多少问题包含搜索所有邮件的代码。
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.uids(A(date_lt=datetime.date.today() - datetime.timedelta(days=2))))
https://github.com/ikvk/imap_tools https://github.com/ikvk/imap_tools
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.