如何删除最近在 python 中发送的邮件?

How to delete most recently mail sent in python?

使用python和imaplib,如何删除最近发送的邮件? 我有这个:

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

提前致谢!

您需要使用 select 方法打开具有读写权限的相应文件夹。如果您不想将您的消息标记为已读,则需要使用检查方法。

排序命令可用,但不保证IMAP 服务器支持。例如,Gmail 不支持 SORT 命令。

要尝试排序命令,您可以将 M.search(None, 'ALL') 替换为 M.sort(search_critera, 'UTF-8', 'ALL')

那么 search_criteria 将是一个像这样的字符串:

search_criteria = 'DATE' #Ascending, most recent email last
search_criteria = 'REVERSE DATE' #Descending, most recent email first
search_criteria = '[REVERSE] sort-key' #format for sorting

根据 RFC5256 这些是有效的 sort-key:

"ARRIVAL" / "CC" / "DATE" / "FROM" / "SIZE" / "SUBJECT" / "TO"

我找到了适合我的解决方案。获得发送邮箱访问权限后,我需要找到一条具有 fetch() 功能的消息,然后删除具有 expunge() 功能的电子邮件。来自 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.

我的代码:

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()