Update:我的代码在Python2.6.5下工作,但不是Python3(我使用的是3.4.1).

我无法在"所有邮件"或"已发送邮件"文件夹中搜索邮件-我遇到一个例外:

imaplib.error: SELECT command error: BAD [b'Could not parse command']

我的代码:

import imaplib
m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
m.login("myemail@gmail.com","mypassword")
m.select("[Gmail]/All Mail")

使用m.select("[Gmail]/Sent Mail")也不管用.

但从收件箱中阅读是有效的:

import imaplib
m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
m.login("myemail@gmail.com","mypassword")
m.select("inbox")
...

我用过邮件.list()命令验证文件夹名称是否正确:

b'(\\HasNoChildren) "/" "INBOX"', 
b'(\\Noselect \\HasChildren) "/" "[Gmail]"',
b'(\\HasNoChildren \\All) "/" "[Gmail]/All Mail"', 
b'(\\HasNoChildren \\Drafts) "/" "[Gmail]/Drafts"', 
b'(\\HasNoChildren \\Important) "/" "[Gmail]/Important"', 
b'(\\HasNoChildren \\Sent) "/" "[Gmail]/Sent Mail"', 
b'(\\HasNoChildren \\Junk) "/" "[Gmail]/Spam"', 
b'(\\HasNoChildren \\Flagged) "/" "[Gmail]/Starred"', 
b'(\\HasNoChildren \\Trash) "/" "[Gmail]/Trash"'

I'm following the solutions from these questions, but they don't work for me:
imaplib - What is the correct folder name for Archive/All Mail in Gmail?

I cannot search sent emails in Gmail with Python

以下是一个完整的示 routine 序,其中包括doesn't work on Python 3:

import imaplib
import email

m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
m.login("myemail@gmail.com","mypassword")
m.select("[Gmail]/All Mail")

result, data = m.uid('search', None, "ALL") # search all email and return uids
if result == 'OK':
    for num in data[0].split():
        result, data = m.uid('fetch', num, '(RFC822)')
        if result == 'OK':
            email_message = email.message_from_bytes(data[0][1])    # raw email text including headers
            print('From:' + email_message['From'])

m.close()
m.logout()

将引发以下异常:

Traceback (most recent call last):
File "./eport3.py", line 9, in <module>
m.select("[Gmail]/All Mail")
File "/RVM/lib/python3/lib/python3.4/imaplib.py", line 682, in select
typ, dat = self._simple_command(name, mailbox)
File "/RVM/lib/python3/lib/python3.4/imaplib.py", line 1134, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/RVM/lib/python3/lib/python3.4/imaplib.py", line 965, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SELECT command error: BAD [b'Could not parse command']

下面是对应的Python 2版本that works:

import imaplib
import email

m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
m.login("myemail@gmail.com","mypassword")
m.select("[Gmail]/All Mail")

result, data = m.uid('search', None, "ALL") # search all email and return uids
if result == 'OK':
    for num in data[0].split():
        result, data = m.uid('fetch', num, '(RFC822)')
        if result == 'OK':
            email_message = email.message_from_string(data[0][1])    # raw email text including headers
            print 'From:' + email_message['From']

m.close()
m.logout()

推荐答案

正如this answer中提到的:

try 使用m.select("[Gmail]/All-Mail""),以便传输双引号.

它在python v3.4.1分钟内有效

import imaplib
import email

m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
m.login("myemail@gmail.com","mypassword")
m.select('"[Gmail]/All Mail"')

result, data = m.uid('search', None, "ALL") # search all email and return uids
if result == 'OK':
    for num in data[0].split():
    result, data = m.uid('fetch', num, '(RFC822)')
    if result == 'OK':
        email_message = email.message_from_bytes(data[0][1])    # raw email text including headers
        print('From:' + email_message['From'])

m.close()
m.logout()

Python-3.x相关问答推荐

PythonPandas -通过知道位置(Loc)而不是索引来删除行

在循环访问XML中的多个层时,xml.etree.Elementree Python3解析器不起作用

被多个\n拆分并保留

以编程方式关闭jupyterlab内核

无法导入名称';核心';来自部分初始化的模块';tensorflow_datasets';(很可能是由于循环导入)

向前/向后移动导致移动行的数据不可见

Django 模型类方法使用错误的 `self`

使用Python按照其组/ID的紧密值的递增顺序映射数据框的两列

我想使用命令提示符安装 cv2

在 python f-string 中使用 \u

python2和python3中的列表生成器

如何在 VSCode 的在 Cloud Run Emulator 上运行/调试构建设置中添加 SQL 连接

每个数据行中每个数据帧值的总和

django rest框架中的save()、create()和update()有什么区别?

在 Pandas 数据框中显示对图

如何使用已打开并使用登录凭据登录的浏览器

如何替换 Python pathlib.Path 中的子字符串?

如何在 QGraphicsView 中启用平移和zoom

在 macbook pro M1 上安装 Tensorflow 时出现zsh:非法硬件指令 python

Python 3中星型导入的函数形式是什么