【问题标题】:How to check whether IMAP-IDLE works?如何检查 IMAP-IDLE 是否有效?
【发布时间】:2013-08-08 19:45:26
【问题描述】:

我注意到我的 IMAP 服务器似乎支持 IDLE,但通知延迟到达。所以我问自己:如何检查 IDLE 是否有效(或者它是我的邮件客户端)?

【问题讨论】:

    标签: imap imaplib


    【解决方案1】:

    受http://pymotw.com/2/imaplib/ 的启发,您可以使用以下 Python 脚本检查通过 IDLE 的推送通知是否以及如何快速工作:

    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
    

    创建这些文件后,只需调用

    python imaplib_idlewait.py

    请注意,如果您按 CTRL+C,此脚本不会正常关闭(readline() 是阻塞的,并且不会被 close() 终止),但是,对于测试它应该足够好。

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

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 2019-08-21
      • 2010-12-20
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多