Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting n most recent emails using IMAP and Python

Tags:

python

email

imap

I'm looking to return the n (most likely 10) most recent emails from an email accounts inbox using IMAP.

So far I've cobbled together:

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 is returning email headers fine, but it seems to be a semi-random collection of emails that it gets, not the 10 most recent.

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.

like image 607
mrmagooey Avatar asked Apr 12 '11 08:04

mrmagooey


2 Answers

This is the code to get the emailFrom, emailSubject, emailDate, emailContent etc..

import imaplib, email, os
user = "[email protected]"
password = "pass"
imap_url = "imap.gmail.com"
connection = imaplib.IMAP4_SSL(imap_url)
connection.login(user, password)
result, data = connection.uid('search', None, "ALL")
if result == 'OK':
    for num in data[0].split():
        result, data = connection.uid('fetch', num, '(RFC822)')
        if result == 'OK':
            email_message = email.message_from_bytes(data[0][1])
            print('From:' + email_message['From'])
            print('To:' + email_message['To'])
            print('Date:' + email_message['Date'])
            print('Subject:' + str(email_message['Subject']))
            print('Content:' + str(email_message.get_payload()[0]))
connection.close()
connection.logout()        
like image 170
tshubham7 Avatar answered Sep 23 '22 18:09

tshubham7


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

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

Then search_criteria would 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 these are valid sort-key's:
"ARRIVAL" / "CC" / "DATE" / "FROM" / "SIZE" / "SUBJECT" / "TO"

Notes:
1. charset is required, try US-ASCII or UTF-8 all others are not required to be supported by the IMAP server
2. search critera is also required. The ALL command is a valid one, but there are many. See more at http://www.networksorcery.com/enp/rfc/rfc3501.txt

The world of IMAP is wild and crazy. Good luck

like image 36
rfadams Avatar answered Sep 22 '22 18:09

rfadams