IMAP 中的数据响应使用 Python

Data responses in IMAP using Python

亲爱的 Stack Overflow 用户,

我的问题是关于如何在 python 中使用 imap 命令的返回数据(在本例中打印收件箱中的邮件数量)。我能在网上找到的内容仅限于以下两种描述:

Discription 1

Discription 2

阅读这些解释,我仍然不知道如何使用 EXISTS 响应,因为我刚刚开始编程(在 Uni 学习了一个学期的 C 编程)。 所以,如果有人能帮助我理解如何在 python 中使用 imap 命令的响应,那就太棒了。我确实更愿意理解响应的原理,而不是只解决这个一次性问题,这样我就可以在不同的情况下使用响应(那时其他人也可以应用它)。

到目前为止,我在 Raspberry Pi 上编写的(基本)代码包括我卡在 EXISTS 的地方(在两个问号之间):

import imaplib
server = imaplib.IMAP4_SSL(‘imap.gmail.com’)
server.login(‘USERNAME’, ‘PASSWORD’)
server.list()
server.select(‘inbox’)

print ‘%d messages in the inbox’ %d ??EXISTS??

希望我不是唯一想知道这个的人!

亲切的问候,

我。范戴克

P.S。 我更新后的代码如下(错误是:TypeError: not all arguments converted during string formatting):

import imaplib
server = imaplib.IMAP4_SSL('imap.gmail.com')
server.login('USERNAME', 'PASSWORD')
server.list()
server.select('inbox')
number_of_messages = server.select("inbox")

print '%s messages' % number_of_messages

select 函数 returns 来自 EXIST 响应的数字。几乎所有 imaplib 命令 return 两个值,typedata.

来自documentation

Each command returns a tuple: (type, [data, ...]) where type is usually 'OK' or 'NO', and data is either the text from the command response, or mandated results from the command. Each data is either a string, or a tuple. If a tuple, then the first part is the header of the response, and the second part contains the data (ie: ‘literal’ value).

select,在它的数据列表中 returns 来自 EXISTS 响应的数字,显然是一个字符串。您需要从列表中提取项目,并将其转换为字符串:

typ, dat = inbox.select()
number_of_messages = int(dat[0])