Getting the n most recent emails using IMAP and Python

I want to return the n (most likely 10) most recent emails from an email inbox using IMAP.

So far I have united:

import imaplib from email.parser import HeaderParser M = imaplib.IMAP4_SSL('my.server') user = 'username' password = 'password' M.login(user, password) M.search(None, 'ALL') for i in range (1,10): data = M.fetch(i, '(BODY[HEADER])') header_data = data[1][0][1] parser = HeaderParser() msg = parser.parsestr(header_data) print msg['subject'] 

This returns the headers of the letters in order, but it seems to be a semi-random set of letters he receives, not the 10 most recent ones.

If this helps, I connect to the Exchange 2010 server. Other approaches are also welcome, IMAP just seemed the most appropriate, given that I only wanted to read emails that didn't send.

+7
source share
2 answers

A sort command is available, but it is not guaranteed to support IMAP server. For example, Gmail does not support the SORT command.

To try the sort command, you must replace:
M.search(None, 'ALL')
from
M.sort(search_critera, 'UTF-8', 'ALL')

Then search_criteria will be a string like:

 search_criteria = 'DATE' #Ascending, most recent email last search_criteria = 'REVERSE DATE' #Descending, most recent email first search_criteria = '[REVERSE] sort-key' #format for sorting 

According to RFC5256 , they are valid sort-key :
"ARRIVAL" / "CC" / "DATE" / "FROM" / "SIZE" / "SUBJECT" / "TO"

Notes:
1. requires encoding, try US-ASCII or UTF-8 , all the rest should not be supported by the IMAP server

2. A search criteria is also required. The ALL command is valid, but there are many. See http://www.networksorcery.com/enp/rfc/rfc3501.txt for more details.

The world of IMAP is wild and crazy. Good luck.

+10
source

this is work for me ~

 import imaplib from email.parser import HeaderParser M = imaplib.IMAP4_SSL('my.server') user = 'username' password = 'password' M.login(user, password) (retcode, messages) =M.search(None, 'ALL') news_mail = get_mostnew_email(messages) for i in news_mail : data = M.fetch(i, '(BODY[HEADER])') header_data = data[1][0][1] parser = HeaderParser() msg = parser.parsestr(header_data) print msg['subject'] 

and this gives a new email function:

 def get_mostnew_email(messages): """ Getting in most recent emails using IMAP and Python :param messages: :return: """ ids = messages[0] # data is a list. id_list = ids.split() # ids is a space separated string #latest_ten_email_id = id_list # get all latest_ten_email_id = id_list[-10:] # get the latest 10 keys = map(int, latest_ten_email_id) news_keys = sorted(keys, reverse=True) str_keys = [str(e) for e in news_keys] return str_keys 
-one
source

All Articles