Chan
Chan

Reputation: 4291

How to sort email by time in imaplib using python

I would like to sort the emails by arrival time.

Here is the code:

data = get_credential('info.txt')
imap_conn = create_connection(data, 'outlook.office365.com')
imap_conn.select('INBOX', readonly=False)
result, messages = imap_conn.sort('ARRIVAL', 'UTF-8', 'FROM [email protected] SINCE "'+(datetime.date.today()-datetime.timedelta(4)).strftime('%d-%b-%Y')+'" 

It returns the following error:

File "C:\Program Files\Python37\lib\imaplib.py", line 794, in sort
    typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
  File "C:\Program Files\Python37\lib\imaplib.py", line 1196, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Program Files\Python37\lib\imaplib.py", line 1027, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: SORT command error: BAD [b'Command Error. 12']

How to solve the problem?

Is the input charset UTF-8 correct? How to get it from messages?

Upvotes: 3

Views: 2075

Answers (1)

Max
Max

Reputation: 10985

Office365 doesn't support the SORT extension.

* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CLIENTACCESSRULES CLIENTNETWORKPRESENCELOCATION BACKENDAUTHENTICATE CHILDREN IDLE NAMESPACE LITERAL+

You should check CAPABILITY before using any extensions.

Upvotes: 2

Related Questions