简体   繁体   English

如何从IMAP服务器获取最近的10条消息?

[英]How to fetch last 10 messages from IMAP server?

I use imaplib2 library to search the last 10 messages with such command: 我使用imaplib2库通过以下命令搜索最后10条消息:

imap_client.search(None, '{}:{}'.format(last_uid, last_uid - 9))

But to get last_uid I need exec every time command like this: 但是要获取last_uid我需要每次执行exec都是这样的:

imap_client.select("INBOX", readonly=True)

to get last UID. 获取最后的UID。

Are the any ways to: 有什么方法可以做到:

  1. get last UID without select() command fetch last 10 messages 在没有select()命令的情况下获取最后的UID获取最后10条消息
  2. without last UID. 没有最后一个UID。 Maybe there are any search criterias like 'LAST' or '-10:'? 也许有类似“ LAST”或“ -10:”的搜索条件?

I can not exec command like this client.search(None, 'ALL') , because IMAP server have more than 50K messages. 我无法执行像client.search(None, 'ALL')这样的命令,因为IMAP服务器有超过5万条消息。

You can get the last UID using the STATUS (UIDNEXT) command. 您可以使用STATUS (UIDNEXT)命令获取最后的UID。 However, you have to select the mailbox in order to retrieve messages, and when you issue SELECT, you'll get a message count back, which the Python imaplib's select returns. 但是,您必须选择邮箱才能检索消息,并且在发出SELECT时,您将获得消息计数,Python imaplib的select返回该消息计数。

So all you need is: 因此,您需要做的是:

(status, response_text) = mailbox.select("inbox")
# response_text usually contains only one bytes element that denotes
# the message count in an ASCII string
message_count = int(response_text[0].decode("ascii"))

and then you can fetch the messages by index from message_count - 9 through message_count . 然后您可以通过message_countmessage_count - 9的索引中获取消息。

Note that messages are index starting at one. 请注意,消息是从1开始的索引。

For any future travelers who seek an answer to this, I came up with code from the hint given by @arnt. 对于未来寻求答案的旅行者,我从@arnt给出的提示中得出了代码。

svr = imaplib.IMAP4_SSL(server)
if svr.login(user=user, password=password):
    print('User ' + user + ' logged in successfully.')
else:
    print('Login for the user ' + user + " was denied. Please check your credentials.")

x = svr.select('inbox', readonly=True)
num = x[1][0].decode('utf-8')
#from here you can start a loop of how many mails you want, if 10, then num-9 to num
resp, lst = svr.fetch(num, '(RFC822)')
body = lst[0][1]
email_message = email.message_from_bytes(body)

For me this was quite handy as I was accessing an email with more than 67000 emails in it. 对我来说,这很方便,因为我正在访问包含67000多个电子邮件的电子邮件。

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

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