使用 imaplib (gmail) 删除电子邮件
Deleting an email using imaplib (gmail)
下面的代码是我对如何使用 imaplib 删除电子邮件的理解。它包括在删除之前将电子邮件移动到 'trash',我相信这是使用 gmail 时的要求。
但是正如您所看到的,我似乎处于标签修改阶段。我在堆栈上查看了其他类似的主题,尽管尝试了多个建议的解决方案,但我无法解决这个问题。
>>> import imaplib
>>> server = imaplib.IMAP4_SSL(GMAIL_IMAP)
>>> server.login(EMAIL, PASSWORD)
('OK', [b'anautomatedemail@gmail.com authenticated (Success)'])
>>> server.select("INBOX")
('OK', [b'17'])
>>> status, uids = server.uid("search", None, "ALL")
>>> uids
[b'1 2 3 4 5 6 7 8 9 10 15 16 17 18 19 43 44']
uids = [uid for uid in uids[0].split()]
>>> uids
[b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'10', b'15', b'16', b'17', b'18', b'19', b'43', b'44']
>>> server.store(uids[-1], "X-GM-LABELS", "\Trash")
('OK', [None])
>>> server.store(uids[-1], "+FLAGS", "\Deleted")
('OK', [None])
>>> server.expunge()
('OK', [None])
>>> server.close()
('OK', [b'Returned to authenticated state. (Success)'])
>>> server.logout()
('BYE', [b'LOGOUT Requested'])
您混合了 UID 和序列号。
您请求 UID SEARCH,请取回 UID。您还需要使用 UID STORE:
server.uid("store", uids[-1], "X-GM-LABELS", "\Trash")
其他存储命令依此类推。仅在 Gmail 上,当您以这种方式将其移至垃圾箱时,您无需费心使用 \Deleted 和 Expunge 命令。服务器应该会自动为您执行此操作。
下面的代码是我对如何使用 imaplib 删除电子邮件的理解。它包括在删除之前将电子邮件移动到 'trash',我相信这是使用 gmail 时的要求。
但是正如您所看到的,我似乎处于标签修改阶段。我在堆栈上查看了其他类似的主题,尽管尝试了多个建议的解决方案,但我无法解决这个问题。
>>> import imaplib
>>> server = imaplib.IMAP4_SSL(GMAIL_IMAP)
>>> server.login(EMAIL, PASSWORD)
('OK', [b'anautomatedemail@gmail.com authenticated (Success)'])
>>> server.select("INBOX")
('OK', [b'17'])
>>> status, uids = server.uid("search", None, "ALL")
>>> uids
[b'1 2 3 4 5 6 7 8 9 10 15 16 17 18 19 43 44']
uids = [uid for uid in uids[0].split()]
>>> uids
[b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'10', b'15', b'16', b'17', b'18', b'19', b'43', b'44']
>>> server.store(uids[-1], "X-GM-LABELS", "\Trash")
('OK', [None])
>>> server.store(uids[-1], "+FLAGS", "\Deleted")
('OK', [None])
>>> server.expunge()
('OK', [None])
>>> server.close()
('OK', [b'Returned to authenticated state. (Success)'])
>>> server.logout()
('BYE', [b'LOGOUT Requested'])
您混合了 UID 和序列号。
您请求 UID SEARCH,请取回 UID。您还需要使用 UID STORE:
server.uid("store", uids[-1], "X-GM-LABELS", "\Trash")
其他存储命令依此类推。仅在 Gmail 上,当您以这种方式将其移至垃圾箱时,您无需费心使用 \Deleted 和 Expunge 命令。服务器应该会自动为您执行此操作。