我注意到我的IMAP服务器似乎支持IDLE,但通知迟到了.所以我问自己:我如何检查IDLE是否有效(或者是我的邮件客户端)?
受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"
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
的Settings.ini
[server]
hostname: yourserver.com
[account]
username: yourmail@yourserver.com
password: yoursecretpassword
Run Code Online (Sandbox Code Playgroud)
创建这些文件后,只需调用即可
python imaplib_idlewait.py
请注意,如果按CTRL + C(readline()阻塞并且没有被close()终止),此脚本不会正常关闭,但是,对于测试它应该足够好.
另请注意,大多数邮件服务器在30分钟后终止连接.之后你必须重新打开连接,例如在此处演示:http://blog.mister-muffin.de/2013/06/05/reliable-imap-synchronization-with-idle-support
| 归档时间: |
|
| 查看次数: |
4386 次 |
| 最近记录: |