2013-08-07 105 views

回答

5

通过http://pymotw.com/2/imaplib/的启发,你可以用下面的Python脚本检查,并通过无功推的速度有多快通知:

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: [email protected] 
password: yoursecretpassword 

创建这些文件后,只需拨打

蟒蛇imaplib_idlewait.py

请注意,这个脚本没有正常关闭,如果您按CTRL + C(的ReadLine()阻塞,是不是由close()终止,但是,测试它应该足够好。

另请注意,大多数邮件服务器在30分钟后终止连接。之后,你必须重新打开连接,例如像这里演示的那样:http://blog.mister-muffin.de/2013/06/05/reliable-imap-synchronization-with-idle-support