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
This commit is contained in:
2026-07-02 19:53:26 +08:00
parent e2826a3e3b
commit 82403de6df

View File

@@ -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()