Search code examples
imaplib

search archived messages using imap


The following code will search for a string from emails found in "inbox". My problem is that I need to search across all folders. M.selct("All") does not work.

import imaplib

M = imaplib.IMAP4_SSL('imap.gmail.com')
M.login('sh.ak@gmail.com', 'xxx')
M.select("Inbox") 

ping=M.uid('search', None, '(HEADER Subject "Monthly Report")')

This is as good as typing this in google search bar:

Subject: "Monthly Report" in:inbox

But I need the search without "in:inbox" If I type M.select("All")

I get the following error:

error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

How do I search across all mail including archived?


Solution

  • Select the "[Gmail]/All Mail" folder and search it.