Search code examples
pythongmailimap

Search in Gmail using imaplib


import imaplib

user = raw_input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")


m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("[Gmail]/Inbox") # here you a can choose a mail box like INBOX instead
m.search("NEW")

I'm trying to select only new messages in Gmail, via imap in Python. Problem is, I always get the following error:

imaplib.error: command SEARCH illegal in state AUTH

I googled it and read that I'd have to use imap4, but I'm already using it I can't really figure out how to solve it.


Solution

  • The problem seems to be that there is no mailbox called [Gmail]/Inbox. It is possible to get a listing of all valid mailboxes by calling m.list().

    I discovered this by using Python's interactive shell (with Python 2.6), where it shows the response from the IMAP server for each IMAP operation.

    Note: When using the Python interactive shell, importing pprint and calling pprint.pprint(m.<method of m>(<params>)) would probably be a good idea for some IMAP commands which send back lots of information.