Search Gmail with 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 am trying to select only new messages in Gmail, via imap in Python. The problem is that I always get the following error:

imaplib.error: SEARCH command is illegal in AUTH state

I looked at it and read that I have to use imap4, but I already use it, I can not figure out how to solve it.

+4
source share
4 answers

The problem is that there is no mailbox named [Gmail]/Inbox . You can get a list of all valid mailboxes by calling m.list() .

I discovered this using the Python interactive shell (since 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>)) probably be a good idea for some IMAP commands that send a lot of information.

+4
source

One more thing - the imaplib select () function selects the default INBOX for you, it seems cleaner.

http://docs.python.org/library/imaplib.html#imaplib.IMAP4.select

+1
source
 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"') 
+1
source

For me, it had "[Gmail]", which was problematic:

those. change this:

 m.select("[Gmail]/Inbox") 

:

 m.select("Inbox") 

Despite this, using m.list () as the person suggested above is a good start.

0
source

Source: https://habr.com/ru/post/1341894/


All Articles