Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen for incoming emails in real time

Tags:

python

imaplib

Most IMAP email clients have the ability to receive emails automatically in real time, without refreshing on a fixed interval. This is because the email client keeps a connection open to the server, and if there isn't any email data exchanged to keep the connection alive, the email client will send a NOOP packet on a fixed interval (just like other TCP protocols have their own keepalive packets). In Thunderbird, this behavior can be controlled by the 'Allow immediate server notifications when new messages arrive' option.

I'm writing a Python program that needs to know instantly when emails come in. The standard procedure for receiving emails is (after connection and login) select('inbox'), search(None, 'ALL') (or some specific search term), and fetch(). I can't figure out how to listen for new emails in real time. Every guide I've read suggests running the search() and fetch() functions in a loop. I've tried running the read() function while sending myself emails, but I have never seen read() output any data. Perhaps the server needs to know to push emails to the client? I haven't been able to confirm or refute this theory.

How can I instantly receive new emails with imaplib, or a similar Python library?

While I did not know at the time of originally posting this question, I was looking for a solution that implements the IMAP IDLE command, as defined in RFC2177.

like image 688
Billy Avatar asked Jul 14 '19 22:07

Billy


2 Answers

Since you want to fetch emails asynchronously you should use the below library

https://github.com/bamthomas/aioimaplib

like image 84
Tarun Lalwani Avatar answered Oct 14 '22 09:10

Tarun Lalwani


I used aioimaplib in my code, but imaplib2 also supposedly supports IDLE; see: https://web.archive.org/web/20090814230913/http://blog.hokkertjes.nl/2009/03/11/python-imap-idle-with-imaplib2/

like image 27
Billy Avatar answered Oct 14 '22 09:10

Billy