我注意到我的 IMAP 服务器似乎支持 IDLE,但通知迟到了。所以我问自己:如何检查 IDLE 是否有效(或者它是我的邮件客户端)?
问问题
5779 次
1 回答
7
受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()
设置.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
于 2013-08-07T12:22:58.893 回答