简体   繁体   English

我无法使用Python在Gmail中搜索已发送的电子邮件

[英]I cannot search sent emails in Gmail with Python

I am trying to search for messages in the Sent (actually i care for both) but I only get incoming messages. 我正在尝试搜索已发送的消息(实际上我关心两者),但我只收到传入的消息。 For the time being i have 暂时我有

imap_conn.select()
str_after = after.strftime('%d-%b-%Y')
typ, msg_ids = imap_conn.search('UTF-8','SINCE',str_after)

Which gives equivalent results with this 这给出了相同的结果

imap_conn.select('INBOX')

When I replace INBOX with ALL or SENT I get: command SEARCH illegal in state AUTH, only allowed in states SELECTED 当我用ALL或SENT替换INBOX时,我得到:命令SEARCH在状态AUTH中是非法的,只允许在SELECTED状态下

Man, the error message is so misleading. 伙计,错误信息是如此误导。 What it's really saying is that you have tried to select an invalid folder name hence the search operation fails. 它真正说的是你试图选择一个无效的文件夹名称,因此搜索操作失败。

To verify/check the current valid folders/labels do something like: 要验证/检查当前有效的文件夹/标签,请执行以下操作:

Using ImapClient 使用ImapClient

from imapclient import IMAPClient
## Connect, login and select the INBOX
imap_conn = IMAPClient('imap.gmail.com', use_uid=True, ssl=ssl)
imap_conn.login(USERNAME, PASSWORD)

print(imap_conn.list_folders())

Using imaplib 使用imaplib

import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername@gmail.com', 'mypassword')
print(mail.list())

After I could see what folder names it was expecting, all was well. 在我看到它所期待的文件夹名称之后,一切都很顺利。

import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com',993)
obj.login('userid','password')
obj.select('Sent')  # <-- response like ('OK', ['74']) --> total no. of mail in sent folder
obj.uid('SEARCH',None,'All') # <-- Returns the list of uids of the sent folder.

You need to use: imap_conn.select('[Gmail]/Sent Mail') 您需要使用:imap_conn.select('[Gmail] /已发邮件')

Just wanted to point this out for future users who see this. 只是想为未来的用户指出这一点。 It's hidden in the comments. 它隐藏在评论中。

Make sure you use the extra quotes in your string: 确保在字符串中使用额外的引号:

imap_conn.select('"[Gmail]/Sent Mail"')  

That worked for me. 这对我有用。

Need to use print imap_conn.list() . 需要使用print imap_conn.list() Tags are language based. 标签是基于语言的。 for example in spanish is [Gmail]/Todos 例如西班牙语是[Gmail]/Todos

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

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