title: Getting n most recent emails using IMAP and Python
body: <p>I'm looking to return the n (most likely 10) most recent emails from an email accounts inbox using IMAP.</p>
  
  <p>So far I've cobbled together:</p>
  
  <pre><code>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']
  </code></pre>
  
  <p>This is returning email headers fine, but it seems to be a semi-random collection of emails that it gets, not the 10 most recent.</p>
  
  <p>If it helps, I'm connecting to an Exchange 2010 server. Other approaches also welcome, IMAP just seemed the most appropriate given that I only wanted to read the emails not send any.</p>