使用python imaplib2查找自上次检查以来新增的imap邮箱消息?
我正在尝试写一个程序,用来监控一个IMAP邮箱,并自动把每一封新收到的邮件复制到一个“归档”文件夹里。我使用的是imaplib2这个库,它实现了IDLE命令。下面是我的基本程序:
M = imaplib2.IMAP4("mail.me.com")
M.login(username,password)
lst = M.list()
assert lst[0]=='OK'
for mbx in lst[1]:
print "Mailboxes:",mbx
def process(m):
print "m=",m
res = M.recent()
print res
M.select('INBOX')
M.examine(mailbox='INBOX',callback=process)
while True:
print "Calling idle..."
M.idle()
print "back from idle"
M.close()
M.logout()
这个程序可以正确打印出邮箱列表,并在邮箱第一次发生变化时运行process()函数。但是,recent()的返回结果我看不懂,而且在收到第一封邮件后,我就再也没有收到其他的通知了。
有没有人知道该怎么做?
2 个回答
2
我发现最近的这个函数(recent())有点模糊(这是IMAP本身的问题,不是imaplib2的问题)。感觉在进入空闲状态之前和之后,先把消息编号记录下来比较好,这样就能通过对比找出新消息。
然后可以用fetch(messages,"UID")来获取这些消息的唯一标识符(uid)。
2
可以查看这个例子和相关资料,链接在这里:python-imap-idle-with-imaplib2(这是一个存档的网页)。
这个模块涉及到多线程,所以你需要注意事件的同步,也就是确保不同的任务能够协调好。
这个例子建议你要和事件进行同步,同时邮件处理的部分留给读者自己去实现:
# The method that gets called when a new email arrives.
# Replace it with something better.
def dosync(self):
print "Got an event!"
根据问题的提示,"更好的东西"可以是:
# Replaced with something better.
def dosync(self):
print "Got an event!"
res = self.M.recent()
print res