IMAP 电子邮件 IDLE 停止等待超时持续时间,而是在 Python 中立即循环

IMAP email IDLE stops waiting timeout duration, instead loops instantaneously in Python

我有一个程序可以使用 IMAP IDLE 检查收件箱中的新电子邮件。每当我 运行 它时,它一开始都能完美运行。但是一段时间后,它停止暂停 IDLE 超时时间,而是快速循环第一部分。

from imapclient import IMAPClient
from imap_tools import MailBox, AND

while True:
    try:
        #this is the part that's getting looped every half second when it breaks
        telegram('try portion starting again')

        # Wait for up to 540 seconds for an IDLE response
        responses = server.idle_check(timeout=540)
        if responses:
            telegram('Email Recieved')

            for response in responses:

                if response[0] not in checked_uids:

                    checked_uids.append(response[0])

                    uid = str(response[0])

                    with MailBox(HOST).login(USERNAME, PASSWORD) as mailbox:
                        for msg in mailbox.fetch(AND(uid=uid)):

                            body_text=msg.text

                            telegram(body_text)

其中 telegram() 向我发送电报消息。

因此,当它正常工作时,我会收到一条包含新电子邮件正文的消息,并且每隔 540 秒我会收到一条消息,提示 try: 部分已重新开始。

在我的测试中,它像这样工作了一段时间,然后突然间,我无法辨别,我收到“尝试部分重新开始”消息,每秒重复两次,直到无穷大。意思是,responses = server.idle_check(timeout=540) 部分似乎按预期停止工作

编辑:这是我正在使用的代码的捕获部分。超级简单。我也没有收到任何错误消息,同时程序变得疯狂并如此快速地循环

except KeyboardInterrupt:
    break
except Exception as e:
    print(e)
    telegram(e)

我想出了一个解决方案。我仍然不知道为什么会发生这种情况,但这为我解决了。

我把 server.idle() 放在 try: 代码中。然后我将 server.idle_done() 放在 finally 代码段中。这样,程序每次循环时都会启动空闲,每次结束时都会停止空闲。好像每次都这样,程序会更稳定。

自 0.51.0 imap_tools 具有 IDLE 支持:

https://github.com/ikvk/imap_tools/releases/tag/v0.51.0