imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

user5319825 picture user5319825 · Aug 24, 2016 · Viewed 15.2k times · Source
def connect_imap():
    m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    print("{0} Connecting to mailbox via IMAP...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
    details = login_credentials()
    m.login(details[0], details[1])
    return m


m = connect_imap()
typ, data = m.search(None, 'ALL')
m.close()
m.logout()

The Output of the above code is:

2016-08-24 10:55:34 Connecting to mailbox via IMAP...
    Traceback (most recent call last):
      File "/home/zoikmail/Desktop/test.py", line 25, in <module>
        typ, data = m.search(None, 'ALL')
      File "/usr/lib/python2.7/imaplib.py", line 640, in search
        typ, dat = self._simple_command(name, *criteria)
      File "/usr/lib/python2.7/imaplib.py", line 1088, in _simple_command
        return self._command_complete(name, self._command(name, *args))
      File "/usr/lib/python2.7/imaplib.py", line 838, in _command
        ', '.join(Commands[name])))
    imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED
    [Finished in 1.2s with exit code 1]
    [shell_cmd: python -u "/home/zoikmail/Desktop/test.py"]
    [dir: /home/zoikmail/Desktop]
    [path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games]

What's wrong in the above code?

Answer

Someone picture Someone · Nov 14, 2016

You need to select a mailbox after connecting successfully to the IMAP-Server. Use

m.select()

after connecting and before search.