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,11 +332,11 @@ 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}")
while True: # Add a loop to keep retrying on connection loss
try: try:
handler.connect() handler.connect()
while True: while True:
@ -342,11 +344,12 @@ class MultiIMAPHandler:
handler.process_emails() handler.process_emails()
except ConnectionAbortedError as e: except ConnectionAbortedError as e:
print(str(e)) print(str(e))
time.sleep(30) time.sleep(30) # Sleep for 30 seconds before retrying
except Exception as e: except Exception as e:
print(f"An unexpected error occurred: {str(e)}") print(f"An unexpected error occurred: {str(e)}")
logging.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)}") 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)