title: Listen for incoming emails in real time
body: <p>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 <code>NOOP</code> 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.</p>
  <p>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) <code>select('inbox')</code>, <code>search(None, 'ALL')</code> (or some specific search term), and <code>fetch()</code>. I can't figure out how to listen for new emails in real time. Every guide I've read suggests running the <code>search()</code> and <code>fetch()</code> functions in a loop. I've tried running the <code>read()</code> function while sending myself emails, but I have never seen <code>read()</code> 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.</p>
  <p>How can I instantly receive new emails with imaplib, or a similar Python library?</p>
  <p>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 <a href="https://www.rfc-editor.org/rfc/rfc2177" rel="nofollow noreferrer">RFC2177</a>.</p>