Some server send a BYE or drop the connection after less than 10 minutes (for example, Gmail). The socket timeout has been reduced to 8 minutes and there's now some logic to deal with the BYE IMAP message

This commit is contained in:
Stefano Marinelli 2023-10-22 19:54:25 +02:00
parent 028e77c9ac
commit b85545bb9c

View file

@ -288,6 +288,8 @@ class IMAPHandler:
line = self.mail.readline() line = self.mail.readline()
if line: if line:
print(line.decode('utf-8')) print(line.decode('utf-8'))
if b'BYE' in line:
raise ConnectionAbortedError("Received BYE from server. Trying to reconnect...")
if b'EXISTS' in line: if b'EXISTS' in line:
break break
self.mail.send(b'DONE\r\n') self.mail.send(b'DONE\r\n')
@ -330,23 +332,24 @@ class MultiIMAPHandler:
for thread in threads: for thread in threads:
thread.join() thread.join()
@staticmethod @staticmethod
def monitor_account(handler): def monitor_account(handler):
print(f"Monitoring {handler.email_user}") print(f"Monitoring {handler.email_user}")
logging.info(f"Monitoring {handler.email_user}") logging.info(f"Monitoring {handler.email_user}")
try: while True: # Add a loop to keep retrying on connection loss
handler.connect() try:
while True: handler.connect()
handler.idle() while True:
handler.process_emails() handler.idle()
except ConnectionAbortedError as e: handler.process_emails()
print(str(e)) except ConnectionAbortedError as e:
time.sleep(30) print(str(e))
except Exception as e: time.sleep(30) # Sleep for 30 seconds before retrying
print(f"An unexpected error occurred: {str(e)}") except Exception as e:
logging.error(f"An unexpected error occurred: {str(e)}") print(f"An unexpected error occurred: {str(e)}")
notifier.send_notification("Script Error", f"An unexpected error occurred: {str(e)}") logging.error(f"An unexpected error occurred: {str(e)}")
notifier.send_notification("Script Error", f"An unexpected error occurred: {str(e)}")
break
def shutdown_handler(signum, frame): def shutdown_handler(signum, frame):
print("Shutdown signal received. Cleaning up...") print("Shutdown signal received. Cleaning up...")
@ -410,7 +413,7 @@ def multi_account_main():
global notifier global notifier
notifier = Notifier(providers) notifier = Notifier(providers)
socket.setdefaulttimeout(600) socket.setdefaulttimeout(480)
signal.signal(signal.SIGTERM, shutdown_handler) signal.signal(signal.SIGTERM, shutdown_handler)
signal.signal(signal.SIGINT, shutdown_handler) signal.signal(signal.SIGINT, shutdown_handler)