【问题标题】:How to fetch last 10 messages from IMAP server?如何从 IMAP 服务器获取最后 10 条消息?
【发布时间】:2015-09-21 23:46:16
【问题描述】:

我使用 imaplib2 库通过这样的命令搜索最后 10 条消息:

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

但要获得last_uid,我每次都需要执行这样的命令:

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

获取最后一个 UID。

有什么办法:

  1. get last UID without select() command fetch last 10 messages
  2. 没有最后一个 UID。也许有任何搜索条件,例如“LAST”或“-10:”?

我不能像 client.search(None, 'ALL') 这样执行命令,因为 IMAP 服务器有超过 50K 的消息。

【问题讨论】:

  • @Joe,这不是重复的。我无法执行“所有”标准。感谢这一刻,现在已编辑问题。
  • @Joe:如果“最后”只有一个含义,那将是重复的。 叹息
  • UIDs 不保证是连续的,请改用序列号。选择邮箱时返回的COUNT可以得到最后一个序列号。

标签: python imap imaplib


【解决方案1】:

您可以使用STATUS (UIDNEXT) 命令获取最后一个 UID。但是,您必须选择邮箱才能检索消息,并且当您发出 SELECT 时,您将获得消息计数,Python imaplib 的select 返回。

所以你只需要:

(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"))

然后您可以按索引从message_count - 9message_count 获取消息。

请注意,消息的索引从 1 开始。

【讨论】:

    【解决方案2】:

    对于任何寻求此问题答案的未来旅行者,我从@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)
    

    对我来说,这非常方便,因为我正在访问一封包含超过 67000 封电子邮件的电子邮件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多