2015-07-04 139 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个电子邮件。

相关问题