Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform an IMAP search in Python (using Gmail and imaplib)?

Tags:

python

gmail

imap

In Gmail, I have a bunch of labeled messages.

I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.

c = imaplib.IMAP4_SSL('imap.gmail.com')
c.list()
('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])
c.search(???)

I'm not finding many examples for this sort of thing.

like image 406
Jeremy Dunck Avatar asked Oct 07 '08 15:10

Jeremy Dunck


People also ask

How do I install Imaplib?

imaplib Module of Python: Installation The imaplib module is a pre-installed library of Python that comes with the Python installation packages, and that's why we don't have to do any installation process for installing this library.


2 Answers

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"')
like image 61
Avadhesh Avatar answered Sep 19 '22 16:09

Avadhesh


imaplib is intentionally a thin wrapper around the IMAP protocol, I assume to allow for a greater degree of user flexibility and a greater ability to adapt to changes in the IMAP specification. As a result, it doesn't really offer any structure for your search queries and requires you to be familiar with the IMAP specification.

As you'll see in section "6.4.4. SEARCH Command", there are many things you can specify for search criterion. Note that you have to SELECT a mailbox (IMAP's name for a folder) before you can search for anything. (Searching multiple folders simultaneously requires multiple IMAP connections, as I understand it.) IMAP4.list will help you figure out what the mailbox identifiers are.

Also useful in formulating the strings you pass to imaplib is "9. Formal Syntax" from the RFC linked to above.

The r'(\HasNoChildren) "/"' is a mailbox flag on the root mailbox, /. See "7.2.6. FLAGS Response".

Good luck!

like image 43
cdleary Avatar answered Sep 18 '22 16:09

cdleary