I am trying to write a simple IMAP client, and I want to fetch one newest message. Message with UID 46345 is the newest one in my Inbox, an older message has UID 46346. Because of that my code doesn’t work as I expect it! Why isn’t the newest message have the highest UID? Should I not rely the highest UID having the latest date?
_, data = imap.uid('search', None, "UNSEEN")
latest_email_uid = data[0].split()[-1]
_, data = imap.uid('fetch', latest_email_uid, '(RFC822.HEADER)')
raw_email = data[0][1]
print raw_email
I don’t think the IMAP protocol provides any guarantee that the message UIDs will be allocated in order from oldest message to newest. The UIDs can even change from time to time (generally if the IMAP server has to reindex the mailbox) as long as the UIDVALIDITY changes to notify clients of this fact. You have to look at the date headers on the messages (or perhaps IMAP INTERNALDATE if that’s what you’re interested in) and sort them yourself.