我注意到我的IMAP服务器似乎支持IDLE,但通知迟到了。所以我问自己:我如何检查IDLE是否有效(或者是我的邮件客户端)?
答案 0 :(得分:6)
受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