Getting n most recent emails using IMAP and Python -


i'm looking return n (most 10) recent emails email accounts inbox using imap.

so far i've cobbled together:

import imaplib email.parser import headerparser  m = imaplib.imap4_ssl('my.server') user = 'username' password = 'password' m.login(user, password) m.search(none, 'all') 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 returning email headers fine, seems semi-random collection of emails gets, not 10 recent.

if helps, i'm connecting exchange 2010 server. other approaches welcome, imap seemed appropriate given wanted read emails not send any.

the sort command available, not guaranteed supported imap server. example, gmail not support sort command.

to try sort command, replace:
m.search(none, 'all')
with
m.sort(search_critera, 'utf-8', 'all')

then search_criteria string like:

search_criteria = 'date' #ascending, recent email last search_criteria = 'reverse date' #descending, recent email first  search_criteria = '[reverse] sort-key' #format sorting 

according rfc5256 these valid sort-key's:
"arrival" / "cc" / "date" / "from" / "size" / "subject" / "to"

notes:
1. charset required, try us-ascii or utf-8 others not required supported imap server
2. search critera required. all command valid one, there many. see more @ http://www.networksorcery.com/enp/rfc/rfc3501.txt

the world of imap wild , crazy. luck


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -