简体   繁体   English

使用imaplib删除gmail中的电子邮件时出现问题

[英]Problem deleting emails in gmail using imaplib

I try to remove message from inbox folder and all alright, but when i switched to All Mail folder the removing does not work. 我尝试从收件箱文件夹中删除邮件,一切正常,但当我切换到所有邮件文件夹时删除不起作用。 expunge() method returns ('OK', [None]) and message was not removed: expunge()方法返回('OK', [None])并且未删除消息:

>>>import imaplib
>>>server = imaplib.IMAP4_SSL('imap.gmail.com','993')
>>>server.login('likvidator89@gmail.com','Password')
>>>server.select('inbox')
>>>for i in server.search(None,'all')[1][0].split():
...    print i+"\n"+server.fetch(i,'(BODY[HEADER.FIELDS (Subject)])')[1][0][1]
...
#  that how i know what UID hame my message? I select by subject
#....
#28
#Subject: 1 Question Has 1 Answer - Stack Overflow
#
#
#29
#Subject: 2222222222
#...
>>>server.store(29,'+FLAGS','\\Deleted')
#('OK', ['29 (FLAGS (\\Seen \\Deleted))'])
>>>server.expunge()
#('OK', ['29'])
>>> server.select('[Gmail]/All Mail')
('OK', ['47'])
>>> for i in server.search(None,'all')[1][0].split():
...  print i+"\n"+server.fetch(i,'(BODY[HEADER.FIELDS (Subject)])')[1][0][1]
... 
#....
#
#46
#Subject: 2222222222
#
#
#47
#Subject: 3333333333333333
#
#....
>>> server.store(47,'+FLAGS','\\Deleted')
('OK', ['47 (FLAGS (\\Seen \\Deleted))'])
>>> server.expunge()
('OK', [None])

it moves all the mail in a given gmail label to the gmail Trash 它将给定gmail标签中的所有邮件移动到gmail Trash

#!usr/bin/python
import email, imaplib

user = 'xxx'
pwd = 'xxx'

m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)

m.select("some_gmail_label")
m.store("1:*",'+X-GM-LABELS', '\\Trash')

m.expunge() # should be useless, but gmail server says it is ok

Remember to refresh your gmail interface cause it has cache 请记住刷新g​​mail界面,因为它有缓存

As it says on the gmail blog site , Google's implementation of IMAP is a bit different. 正如它在gmail博客网站上所说,谷歌的IMAP实现有点不同。 When you follow the instructions for getting more usual semantics, does it help? 当您按照说明获取更常用的语义时,它有帮助吗?

There are also some more obscure options for those of you who want to make Gmail's IMAP work more like traditional IMAP providers: you can turn off auto-expunge or trash messages when they're no longer visible through IMAP. 对于那些希望让Gmail的IMAP工作更像传统IMAP提供商的人来说,还有一些更加模糊的选项:当通过IMAP不再可见时,您可以关闭自动清除或废弃邮件。

The IMAP protocol allows messages to be marked for deletion, a sort of limbo state where a message is still present in the folder but slated to be deleted the next time the folder is expunged. IMAP协议允许将消息标记为删除,这是一种不明确状态,其中消息仍然存在于文件夹中,但是下次在文件夹被清除时将被删除。 In our standard IMAP implementation, when you mark a message as deleted, Gmail doesn't let it linger in that state -- it deletes (or auto-expunges) it from the folder right away. 在我们的标准IMAP实施中,当您将邮件标记为已删除时,Gmail不会让其在该状态下逗留 - 它会立即从文件夹中删除(或自动删除)该邮件。 If you want the two-stage delete process, after you've enabled this Lab, just select 'Do not automatically expunge messages' under the 'Forwarding and POP/IMAP' tab in Settings. 如果您需要两阶段删除过程,请在启用此实验室后,在“设置”中的“转发和POP / IMAP”标签下选择“不自动删除邮件”。

Similarly, most IMAP systems don't share Gmail's concept of archiving messages (sending messages to the [Gmail]/All Mail folder rather than [Gmail]/Trash). 同样,大多数IMAP系统都不会共享Gmail的归档消息概念(将消息发送到[Gmail] / All Mail文件夹而不是[Gmail] / Trash)。 If you'd prefer that deleted messages not remaining in any other visible IMAP folders are sent to [Gmail]/Trash instead, Advanced IMAP Controls lets you set your preferences this way. 如果您希望将未保留在任何其他可见IMAP文件夹中的已删除邮件发送到[Gmail] /已删除邮件,则可以使用高级IMAP控件以这种方式设置首选项。 In the 'IMAP Access:' section of the 'Forwarding and POP/IMAP' tab, find the 'When a message is deleted from the last visible IMAP folder:' option. 在“转发和POP / IMAP”标签的“IMAP访问:”部分中,找到“当从上一个可见的IMAP文件夹中删除邮件时:”选项。 Select 'Move the message to the Gmail Trash.' 选择“将邮件移至Gmail回收站”。 If you want to take it one step further, you can select 'Immediately delete the message forever.' 如果您想更进一步,可以选择“立即删除邮件”。

With Gmail advanced IMAP controls you can set what happens to messages when you delete them over IMAP. 使用Gmail高级IMAP控件,您可以设置在通过IMAP删除邮件时会发生什么。

Just enable "Advanced IMAP Controls" in Gmail Labs. 只需在Gmail实验室中启用“高级IMAP控件”即可。 The settings page will look like this: 设置页面如下所示:

设置

Then when you mark a message as deleted and expunge as per this answer it will be moved to the bin, permanently deleted, or archived to "All Mail" depending on what setting you selected. 然后,当您将邮件标记为已删除并按照此答案进行清除时,它将被移至邮箱,永久删除或存档为“所有邮件”,具体取决于您选择的设置。

Here is one that works with Gmail and does it very quickly (without store in a for loop). 这是一个适用于Gmail并且非常快速(没有for循环存储)的版本。 Tailor this as you wish, but the idea is all there on how to use select/search and then perform a store, or just select on its own for all items with a specific label/folder: 根据您的意愿定制,但想法是如何使用选择/搜索然后执行商店,或只是自己选择具有特定标签/文件夹的所有项目:

#!/bin/python

import datetime
import imaplib

m = imaplib.IMAP4_SSL("imap.gmail.com")  # server to connect to
print "Connecting to mailbox..."
m.login('gmail@your_gmail.com', 'your_password')

print m.select('[Gmail]/All Mail')  # required to perform search, m.list() for all lables, '[Gmail]/Sent Mail'
before_date = (datetime.date.today() - datetime.timedelta(365)).strftime("%d-%b-%Y")  # date string, 04-Jan-2013
typ, data = m.search(None, '(BEFORE {0})'.format(before_date))  # search pointer for msgs before before_date

if data != ['']:  # if not empty list means messages exist
    no_msgs = data[0].split()[-1]  # last msg id in the list
    print "To be removed:\t", no_msgs, "messages found with date before", before_date
    m.store("1:{0}".format(no_msgs), '+X-GM-LABELS', '\\Trash')  # move to trash
    print "Deleted {0} messages. Closing connection & logging out.".format(no_msgs)
else:
    print "Nothing to remove."

#This block empties trash, remove if you want to keep, Gmail auto purges trash after 30 days.
print("Emptying Trash & Expunge...")
m.select('[Gmail]/Trash')  # select all trash
m.store("1:*", '+FLAGS', '\\Deleted')  #Flag all Trash as Deleted
m.expunge()  # not need if auto-expunge enabled

print("Done. Closing connection & logging out.")
m.close()
m.logout()
print "All Done."

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM