How do I enable push-notification for IMAP (Gmail)

2019-03-08 03:41发布

问题:

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!

回答1:

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



回答2:

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.



回答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).



回答4:

There is simple patch proposed at bugs.python.org implementing RFC 2177 IMAP IDLE 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 :)