0

I have a mailbox and I need to read incoming mails from python. The mail server supports IMAP access so, I'm trying to use python build-in module imaplib.
My code:

import imaplib

def ReadLatest():
    m = imaplib.IMAP4_SSL(<server>)
    m.login(<login>, <password>) # ('OK', ['LOGIN Completed.'])
    if result != 'OK':
        raise Exception("Error connecting to mailbox: {}".format(data))

    result, data = m.select("inbox") # ('OK', ['N']) N - count inbox
    if result != 'OK':
        raise Exception("Error reading inbox: {}".format(data))
    if data == ['0']:
        return None

    #result, data = m.search(None, "ALL") # ('OK', ['1 2']) - numbers of mails
    #m.sort('REVERSE DATE', 'UTF-8', 'ALL') # <-- ERROR!

    latest = data[0].split()[-1]
    result, data = m.fetch(latest, "(RFC822)")
    if result != 'OK':
        raise Exception("Error reading email: {}".format(data))
    <...>
    # further e-mail processing

So, my problem is following: when I'm executing code above, it reads not latest e-mail in case few most recent mails were received simultaneously. I'm checking it by looking thru web interface.
When I put sort by date I got an error: {error}SORT command error: BAD ['Command syntax error, sc=...']. It is not a gmail mailbox, I know that it doesn't support sort command. I don't know does my mailbox support it and don't know how to check it.

Jury
  • 1,227
  • 3
  • 17
  • 30
  • I'm a little confused about what's not working. The code reads the latest email when I try it. Do you mean that you want code to read all the Unread emails? Or all the emails that have arrived since the last time you looked? – Simon Fraser Dec 15 '15 at 10:26
  • It should read always the latest e-mail from inbox. But sometimes... it reads not the latest. For example, when two most recent emails were received in one time. – Jury Dec 15 '15 at 10:40
  • Try sorting on internaldate not date. Date is the date header which could be anything. – Max Dec 15 '15 at 13:41
  • Or, just using the highest ID/UID in the mailbox. IDs/UID are assigned as they arrive in the box, so the newest message, by definition, is the one with the largest ID. – Max Dec 15 '15 at 17:21

0 Answers0