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 INBO开发者_JAVA百科X 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.
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.
One more thing - imaplib's select() function selects INBOX for you by default, seems cleaner.
http://docs.python.org/library/imaplib.html#imaplib.IMAP4.select
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('**label name**') <-- the label in which u want to search message
obj.search(None, 'FROM', '"LDJ"')
For me, it was having "[Gmail]" that was problematic:
I.e. change this:
m.select("[Gmail]/Inbox")
to this:
m.select("Inbox")
Regardless, using m.list() as the person above suggested is a good start.
精彩评论