簡體   English   中英

如何從IMAP服務器獲取最近的10條消息?

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

我使用imaplib2庫通過以下命令搜索最后10條消息:

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

但是要獲取last_uid我需要每次執行exec都是這樣的:

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

獲取最后的UID。

有什么方法可以做到:

  1. 在沒有select()命令的情況下獲取最后的UID獲取最后10條消息
  2. 沒有最后一個UID。 也許有類似“ LAST”或“ -10:”的搜索條件?

我無法執行像client.search(None, 'ALL')這樣的命令,因為IMAP服務器有超過5萬條消息。

您可以使用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_countmessage_count - 9的索引中獲取消息。

請注意,消息是從1開始的索引。

對於未來尋求答案的旅行者,我從@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多個電子郵件的電子郵件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM