Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

imaplib

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?

like image 238
user5319825 Avatar asked Aug 24 '16 05:08

user5319825


1 Answers

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

m.select()

after connecting and before search.

like image 139
Someone Avatar answered Sep 26 '22 15:09

Someone