3

I am trying to access to my emails in Gmail from a python script. The code I use is the following:

import imaplib
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login("username","password")
m.select("[Gmail]/All Mail")

When running this code in python 2, it works fine, I get the list of all my emails. In python 3 hoverer it fails with the error

>>> m.select("[Gmail]/All Mail")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.2/imaplib.py", line 674, in select
    typ, dat = self._simple_command(name, mailbox)
  File "/usr/lib/python3.2/imaplib.py", line 1121, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/lib/python3.2/imaplib.py", line 957, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SELECT command error: BAD [b'[CLIENTBUG] Too many arguments for command']

I have done a bit of testing. It works fine on other folder such as "Inbox" where I get only 400 emails (vs 6000 in "All Mail").

Is it a problem related to the size of the list ? Why is it different in python 2 and 3 ?

Thank you

Martin Trigaux
  • 5,311
  • 9
  • 45
  • 58

1 Answers1

8

Try using m.select('"[Gmail]/All Mail"'), so that the double quotes get transmitted.

I suspect imaplib is not properly quoting the string, so the server gets what looks like two arguments: [Gmail]/All and Mail.

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
Max
  • 10,701
  • 2
  • 24
  • 48
  • Great it works. So it means it would be a problem in Python 3 considering each word as a different argument ? – Martin Trigaux Jul 31 '12 at 16:45
  • 1
    Looks like it's a problem in Python3's imaplib not detecting that the argument needs quoting. In general, if your strings have anything other than letters and numbers, it's a good idea to quote them yourself. – Max Jul 31 '12 at 16:46
  • For me the issue was a _byte string vs unicode string_ one. If you're using unicode strings, ``imaplib`` doesn't detect that it needs quoting, and you should quote it yourself. This is due to a bug in imaplib's ``_checkquote()`` method. For reference, I'm using imaplib 2.58. – Filipe Correia Apr 05 '13 at 12:06
  • 1
    Btw, if you are using unicode strings (or if imaplib is not detecting it needs to quote the folder name for any other reason) you can quote the folder name yourself using imaplib's ``_quote()`` method: ``m.select(m._quote('[Gmail]/All Mail'))``. – Filipe Correia Apr 05 '13 at 12:21