【问题标题】:My Python code runs but doesn't delete selected email from Gmail Inbox我的 Python 代码运行但不会从 Gmail 收件箱中删除选定的电子邮件
【发布时间】:2020-12-18 00:15:08
【问题描述】:

我下面的 Python 代码运行但不会删除我希望从我的测试 gamil\inbox 中删除的选定电子邮件。我不确定我在这里做错了什么。我将非常感谢任何帮助。

import imaplib
import datetime


m = imaplib.IMAP4_SSL("imap.gmail.com")  # server to connect to
print("{0} Connecting to mailbox via IMAP...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
m.login('bb_xxxxx@gmail.com', 'gmail_pass')
 
print("{0} Searching Inbox by sender...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
m.select('Inbox') #select folder to search
status, messages = m.search(None, 'FROM "location-history-noreply@google.com"') # search for specific mails by sender

print("{0} Flagging selected mail as deleted...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
for mail in messages[0].split():
    m.store(mail, "+FLAGS", "\\Deleted")
    m.expunge()
        
print("{0} Done. Closing connection & logging out.".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
m.close()
m.logout()

【问题讨论】:

    标签: python gmail imap


    【解决方案1】:

    在退出 for 循环之前不要运行 expunge。 expunge 重新编号消息 ID,因此您搜索的数字不再对应。

    所以:

    for mail in messages[0].split():
        m.store(mail, "+FLAGS", "\\Deleted")
    m.expunge()
    

    这就是为什么它是一个单独的操作的原因之一。或者在任何地方使用 UID。

    此外,在 gmail 上,删除实际上并不会删除邮件。它仅将其标记为从该标签(收件箱)中删除。如果你想真正删除它,你需要将它移动到垃圾箱文件夹,然后从那里删除它。

    【讨论】:

      【解决方案2】:

      非常感谢麦克斯!你的回答帮助我解决了我的问题。但是,如果我使用“\Deleted”,我会看到邮件已从收件箱中删除,但仍可在“所有邮件”文件夹中使用。这是否意味着它们被永久删除?因此,我尝试使用如下方式移至“垃圾箱”,现在邮件已从收件箱中删除,但已移至“垃圾箱”。

      for mail in messages[0].split():
          #m.store(mail, "+FLAGS", "\\Deleted")
          m.store(mail, '+X-GM-LABELS', '\\Trash')
      m.expunge()
      

      【讨论】:

      • Gmail 并不是真正的 IMAP 服务器。当您将 \Deleted 添加到文件夹中的邮件时,您只是删除了该标签。它将保留在“所有邮件”中(例如,已存档),除非您专门将其移至垃圾箱。从那里,您可以等待它自行删除、自行清空或尝试在设置中配置 Gmail 删除选项。
      猜你喜欢
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 2021-02-20
      相关资源
      最近更新 更多