From 82403de6dfaef00c99636cb3b7d5b2b75071eb00 Mon Sep 17 00:00:00 2001 From: Zichao Lin Date: Thu, 2 Jul 2026 19:53:26 +0800 Subject: [PATCH] fix: check IMAP select() return status before issuing commands - Add _select_mailbox helper that raises on non-OK status - Prevents 'command SEARCH illegal in state AUTH' by catching failed mailbox selection early with a clear error message --- src/email_client.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/email_client.py b/src/email_client.py index 207d234..fedaf0f 100644 --- a/src/email_client.py +++ b/src/email_client.py @@ -48,10 +48,16 @@ def _get_text_from_msg(msg) -> str: return "" +def _select_mailbox(conn, mailbox: str = "INBOX"): + status, data = conn.select(mailbox) + if status != "OK": + raise RuntimeError(f"无法选择邮箱 {mailbox}: {data}") + + def fetch_unseen_emails(account: EmailAccount) -> list[Email]: conn = imaplib.IMAP4_SSL(account.imap_server, account.imap_port) conn.login(account.username, account.password) - conn.select("INBOX") + _select_mailbox(conn) _, data = conn.uid("SEARCH", None, "UNSEEN") uids = data[0].split() if data[0] else [] @@ -80,7 +86,7 @@ def mark_as_seen(account: EmailAccount, uids: list[bytes]): return conn = imaplib.IMAP4_SSL(account.imap_server, account.imap_port) conn.login(account.username, account.password) - conn.select("INBOX") + _select_mailbox(conn) for uid in uids: conn.uid("STORE", uid, "+FLAGS", "\\Seen") conn.logout()