简体   繁体   English

查找自上次检查python imaplib2以来添加到imap邮箱的新邮件?

[英]Find new messages added to an imap mailbox since I last checked with python imaplib2?

I am trying to write a program that monitors an IMAP mailbox and automatically copies every new incoming message into an "Archive" folder. 我正在尝试编写一个监视IMAP邮箱的程序,并自动将每个新传入的邮件复制到“存档”文件夹中。 I'm using imaplib2 which implements the IDLE command. 我正在使用imaplib2来实现IDLE命令。 Here's my basic program: 这是我的基本程序:

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()

It prints the mailboxes properly and runs process() when the first change happens to the mailbox. 它正确打印邮箱,并在邮箱发生第一次更改时运行process()。 But the response from recent() doesn't make sense to me, and after the first message I never get any other notifications. 但是来自recent()的响应对我来说没有意义,并且在第一条消息之后我从未收到任何其他通知。

Anyone know how to do this? 有人知道怎么做吗?

See example and references in python-imap-idle-with-imaplib2 . 请参阅python-imap-idle-with-imaplib2中的示例和引用。 The module involves threading, you should pay attention to event synchronization. 该模块涉及线程,您应该注意事件同步。

The example suggests synchronizing with events, and leaves mail processing to the reader: 该示例建议与事件同步,并将邮件处理留给读者:

# The method that gets called when a new email arrives. 
# Replace it with something better.
def dosync(self):
    print "Got an event!"

Taking a hint from the question, "something better" can be: 从问题中提示, “更好的东西”可以是:

# Replaced with something better.
def dosync(self):
    print "Got an event!"
    res = self.M.recent()
    print res

I am finding that recent() is a bit vague (this is an IMAP vagueness, not imaplib2). 我发现最近的()有点模糊(这是IMAP模糊,而不是imaplib2)。 Seems better to keep a list of message numbers before and after idle, and the difference is new messages. 似乎最好在空闲之前和之后保留消息号列表,区别在于新消息。

Then use fetch(messages,"UID") to get the message uid. 然后使用fetch(messages,“UID”)来获取消息uid。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM