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.