Search code examples
pythonemailgmailimap

imap not allowing use of gmail folders - mail.select folder other than 'inbox'


Basically as stated in the title, I'm using

mail.select("inbox")
result, data = mail.search(None, "ALL")
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest

To get the most recent email from the inbox. Theoretically you can change 'inbox' to another label or folder in gmail (my labels and folders showed up using mail.list() just fine). I want to use my label "Server Status/Leviathan" but it throws the error

Traceback (most recent call last):
  File "E:\False Apparition\Desktop\test3.py", line 18, in <module>
    mail.select("Server Status/Leviathan")
  File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 737, in select
    typ, dat = self._simple_command(name, mailbox)
  File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 1188, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 1019, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SELECT command error: BAD [b'Could not parse command']

Which is different than if the label doesn't exist on gmail...

Traceback (most recent call last):
  File "E:\False Apparition\Desktop\test3.py", line 20, in <module>
    result, data = mail.search(None, "ALL")
  File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 715, in search
    typ, dat = self._simple_command(name, *criteria)
  File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 1188, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 936, in _command
    ', '.join(Commands[name])))
imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

Am I missing something? A library perhaps?


Solution

  • Add quotes around your folder name. Imaplib should do this for you, but it doesn't: mail.select('"folder with space"')