2015-07-04 54 views
0

我用imaplib2庫與這樣的命令搜索過去10個消息:如何從IMAP服務器獲取最後10條消息?

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

但要獲得last_uid我需要Exec的每一次命令是這樣的:

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

得到最後的UID。

是任何方式:

  1. 得到最後的UID沒有select()命令獲取最後10條信息
  2. 沒有最後UID。也許有'LAST'或'-10'等搜索標準嗎?

我不能這樣執行命令client.search(None, 'ALL'),因爲IMAP服務器有超過50K的消息。

+1

[使用IMAP和Python獲取最近的電子郵件]可能的副本(http://stackoverflow.com/questions/5632713/getting-n-most-recent-emails-using-imap-and-python) – Joe

+0

@喬,它不重複。我無法執行'ALL'標準。感謝這一刻,現在編輯問題。 – p2mbot

+1

@Joe:如果只有「last」的一個含義,它將是重複的。 *嘆息* – arnt

回答

2

您可以使用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 - 9通過message_count獲取消息。

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

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個電子郵件。

相關問題