简体   繁体   English

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

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

I have a program to check for new emails in an inbox using IMAP IDLE.我有一个程序可以使用 IMAP IDLE 检查收件箱中的新电子邮件。 Whenever I run it, it works perfectly at first.每当我运行它时,它一开始就完美运行。 But after some time, it stops pausing for the IDLE timeout time and instead rapidly loops through the first part.但是一段时间后,它会在 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)

Where telegram() sends a telegram message to me.电报()向我发送电报消息的地方。

So when this is working correctly, I get a message containing the body of a new email, and every 540 seconds I get a message that the try: portion has started again.因此,当它正常工作时,我收到一条包含新 email 正文的消息,并且每 540 秒我收到一条消息,提示 try: 部分已重新开始。

In my testing, it works just like this for some time then all of a sudden, for no reason I can discern, I get the "try portion starting again" message twice a second repeated to infinity.在我的测试中,它就像这样工作了一段时间,然后突然之间,我无法辨别,我每秒两次收到“尝试重新开始的部分”消息,重复到无穷大。 Meaning, seemingly the responses = server.idle_check(timeout=540) portion stops working as intended意思是,似乎responses = server.idle_check(timeout=540)部分停止按预期工作

edit: here is the catch section of the code I'm using.编辑:这是我正在使用的代码的捕获部分。 Super simple.超级简单。 I'm also not getting any error messages while the program is going crazy and cycling so quickly当程序变得疯狂并且循环如此之快时,我也没有收到任何错误消息

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

I came up with a solution to this.我想出了一个解决方案。 I still don't know why this happened in the first place, but this solved it for me.我仍然不知道为什么会发生这种情况,但这为我解决了它。

I put server.idle() just within the try: code.我将server.idle()放在try:代码中。 Then I put server.idle_done() in a finally code segment.然后我将server.idle_done()放在finally代码段中。 That way, every time the program loops it starts the idle and every time it ends it stops the idling.这样,每次程序循环时都会开始空闲,每次结束时都会停止空闲。 It seems like doing that every time makes the program more stable.似乎每次都这样做会使程序更加稳定。

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

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