Search code examples
pythonimaplib

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 peter@gmail.com 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?


Solution

  • 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.