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:
@@ -48,10 +48,16 @@ def _get_text_from_msg(msg) -> str:
|
|||||||
return ""
|
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]:
|
def fetch_unseen_emails(account: EmailAccount) -> list[Email]:
|
||||||
conn = imaplib.IMAP4_SSL(account.imap_server, account.imap_port)
|
conn = imaplib.IMAP4_SSL(account.imap_server, account.imap_port)
|
||||||
conn.login(account.username, account.password)
|
conn.login(account.username, account.password)
|
||||||
conn.select("INBOX")
|
_select_mailbox(conn)
|
||||||
|
|
||||||
_, data = conn.uid("SEARCH", None, "UNSEEN")
|
_, data = conn.uid("SEARCH", None, "UNSEEN")
|
||||||
uids = data[0].split() if data[0] else []
|
uids = data[0].split() if data[0] else []
|
||||||
@@ -80,7 +86,7 @@ def mark_as_seen(account: EmailAccount, uids: list[bytes]):
|
|||||||
return
|
return
|
||||||
conn = imaplib.IMAP4_SSL(account.imap_server, account.imap_port)
|
conn = imaplib.IMAP4_SSL(account.imap_server, account.imap_port)
|
||||||
conn.login(account.username, account.password)
|
conn.login(account.username, account.password)
|
||||||
conn.select("INBOX")
|
_select_mailbox(conn)
|
||||||
for uid in uids:
|
for uid in uids:
|
||||||
conn.uid("STORE", uid, "+FLAGS", "\\Seen")
|
conn.uid("STORE", uid, "+FLAGS", "\\Seen")
|
||||||
conn.logout()
|
conn.logout()
|
||||||
|
|||||||
Reference in New Issue
Block a user