27

Is there a way to monitor a gmail account using imaplib without polling gmail each time I want to see if there is new mail. Or in other words, I just want the script to be notified of a new message so I can process it right away instead of any lag time between polls.

I see that the IMAP protocol supports this with the IDLE command, but I can't see anything documented with it in the imaplib docs, so any help with this would be great!

cdleary
  • 69,512
  • 53
  • 163
  • 191
RaySl
  • 497
  • 2
  • 7
  • 14

4 Answers4

16

There isn't something in imaplib that does this, AFAIK (disclamer: I know very little about Python), however, it seems that someone has implemented an IDLE extension for Python which has the same interface as imaplib (which you can swap out with no changes to existing code, apparently):

https://github.com/imaplib2/imaplib2

NickD
  • 5,937
  • 1
  • 21
  • 38
casperOne
  • 73,706
  • 19
  • 184
  • 253
6

Check out ProcImap. It's a more abstract framework on top of libimap and libimap2, providing a nice solution to handle IMAP services. Looks like just the stuff you are looking for, and for me as well. I'm right having the same problem with you and just found ProcImap. Gonna try it for myself.

evo
  • 313
  • 1
  • 3
  • 6
  • wow. this is just what I'm looking for to write client-side filters. – vy32 Jan 12 '10 at 02:56
  • @evo did this work for you? I'm also looking to get push notifications about new messages instead of polling. What function in ProcImap did you use? – Alexis Aug 30 '12 at 00:52
  • @Alexis I'd guess [`ImapServer.idle`](https://pythonhosted.org/ProcImap/ProcImap.ImapServer.ImapServer-class.html) – Tobias Kienzler Apr 15 '15 at 10:11
3

This link shows an example of using IMAP IDLE: http://blog.timstoop.nl/2009/03/11/python-imap-idle-with-imaplib2/

It uses the same library linked to in casperOne's answer (imaplib2).

sid
  • 1,012
  • 8
  • 13
2

There is simple patch proposed at bugs.python.org implementing [RFC 2177 IMAP IDLE] 3 command in a synchronous way ( to wait for more than 1 IMAP server you have to use threads or other means of parallel execution ). It uses stdlib select to wait on socket including timeout. This patch will eventually be added to stdlib, but tests have to be written first. The IDLE command is what you need for gmail IMAP push-notification. Hope, this will help :)

Community
  • 1
  • 1
Matus
  • 603
  • 4
  • 6
  • Sadly the patch is still not part of the stdlib. One can use imaplib2 hosted on [sourceforge](https://sourceforge.net/projects/imaplib2/) or imapclient hosted on [github](https://github.com/mjs/imapclient/) – handras Dec 08 '18 at 14:44