سؤال

I noticed that my IMAP server seems to support IDLE but notifications arrive late. So I was asking myself: How can I check whether IDLE works (or is it my mail client)?

هل كانت مفيدة؟

المحلول

Inspired by http://pymotw.com/2/imaplib/, you can use following Python scripts to check if and how fast push notification via IDLE work:

imaplib_connect.py

import imaplib
import ConfigParser
import os

def open_connection(verbose=False):
    # Read the config file
    config = ConfigParser.ConfigParser()
    config.read([os.path.abspath('settings.ini')])

    # Connect to the server
    hostname = config.get('server', 'hostname')
    if verbose: print 'Connecting to', hostname
    connection = imaplib.IMAP4_SSL(hostname)

    # Login to our account
    username = config.get('account', 'username')
    password = config.get('account', 'password')
    if verbose: print 'Logging in as', username
    connection.login(username, password)
    return connection

if __name__ == '__main__':
    c = open_connection(verbose=True)
    try:
        print c
    finally:
        c.logout()
        print "logged out"

imaplib_idlewait.py

import imaplib
import pprint
import imaplib_connect

imaplib.Debug = 4
c = imaplib_connect.open_connection()
try:
    c.select('INBOX', readonly=True)
    c.send("%s IDLE\r\n"%(c._new_tag()))
    print ">>> waiting for new mail..."
    while True:
      line = c.readline().strip();
      if line.startswith('* BYE ') or (len(line) == 0):
        print ">>> leaving..."
        break
      if line.endswith('EXISTS'):
        print ">>> NEW MAIL ARRIVED!"
finally:
    try:
        print ">>> closing..."
        c.close()
    except:
        pass
    c.logout()

settings.ini

[server]
hostname: yourserver.com

[account]
username: yourmail@yourserver.com
password: yoursecretpassword

After creating those files, just call

python imaplib_idlewait.py

Please note, that this scripts does not close gracefully if you press CTRL+C (readline() is blocking and is not terminated by close()), however, for testing it should be good enough.

Also note, that most mail server terminate the connection after 30 minutes. After that you have to re-open the connection, e.g. like demonstrated here: http://blog.mister-muffin.de/2013/06/05/reliable-imap-synchronization-with-idle-support

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top