ikvk / imap_tools

Work with email by IMAP
Apache License 2.0
706 stars 80 forks source link

[Question] How to sort the mails by date #223

Closed meetttttt closed 5 months ago

meetttttt commented 9 months ago

First of all, Amazing repo, Nice work

I have one doubt, I create a a small project using this in backend, I performed all sort of operation like moving mails, copying, deleting the mails. When we move the mail, the uids is changing and sorting is current happening by uid [correct me if I am wrong]. So my question is If I want to sort the mails by date how to do that, providing sample code from the project and the output.

from imap_tools import MailBox

# Get date, subject and body len of all emails from INBOX folder
with MailBox('imap.gmail.com').login('test@gmail.com', 'password') as mailbox:
    for msg in mailbox.fetch(headers_only=True, bulk=True, mark_seen=False, limit=50, reverse=False):
        print(msg.uid, msg.date_str)

This is the output of the current code: image

My question is I want to sort the mails by date and not uid, how to do that??

Thanks

ikvk commented 9 months ago

For now it is impossible on server side at imap_tools. It is good stuff for implement. SORT and THREAD Extensions: https://datatracker.ietf.org/doc/html/rfc5256

Smth like this: mailbox.sort(MailBoxSortOptions.DATE)

ikvk commented 9 months ago

Do you want to implement?

meetttttt commented 9 months ago

Thanks for the response and the docs,

I have written a small code for sorting the date.

I would love to contribute to the repo!!

ikvk commented 5 months ago

Check it: https://github.com/ikvk/imap_tools/releases/tag/v1.6.0 Thanks!

ikvk commented 5 months ago

Small sort example:

from imap_tools import MailBox, SortCriteria

with MailBox('imap.moon').login('ikvk', '123') as mailbox:
    for m in mailbox.fetch(sort=[SortCriteria.FROM_ASC, SortCriteria.SIZE_DESC], mark_seen=False):
        print(m.date, m.subject)