imaplib报错:SEARCH命令在AUTH状态非法,已执行login和select仍出错
解决imaplib.IMAP4.error: SEARCH命令在AUTH状态非法的问题
你遇到的错误核心原因是**imap.select(mailbox)执行失败,但你未做状态检查**,导致连接仍停留在AUTH状态,后续执行SEARCH命令自然触发非法状态报错。
虽然你按login→select→search的顺序执行,但如果传入的mailbox名称无效(比如拼写错误、无权限访问),imap.select()会执行失败,此时连接状态不会切换到SELECTED。
修复方案
必须检查imap.select()的返回值,确认邮箱选择成功后再执行后续的SEARCH、FETCH操作:
修改后的代码如下:
def recieve(self, host: str, port: int, user: str, password: str, mailbox: str, batch_size: int = 0, logout_after: bool = True): """ mailbox gotten from mailboxes() method. a batch size of 0 means all emails, batch sizes get most recent amount of emails in mailbox. """ try: with imaplib.IMAP4_SSL(host, port) as imap: imap.login(user=user, password=password) # 检查邮箱选择是否成功 rv, data = imap.select(mailbox) if rv != 'OK': print(f"ERROR selecting mailbox {mailbox}: {data}") return rv, data = imap.search(None, "ALL") if rv != 'OK': print("ERROR searching emails") return if batch_size == 0: for num in data[0].split(): rv, data = imap.fetch(num, '(RFC822)') print(data) if rv != 'OK': print ("ERROR getting message", num) return else: for num in data[0].split()[-batch_size:]: rv, data = imap.fetch(num, '(RFC822)') print(data) if rv != 'OK': print ("ERROR getting message", num) return imap.close() if logout_after: imap.logout() except Exception as e: raise e
额外建议
- 可先调用
imap.list()获取当前账号可用的邮箱列表,确认传入的mailbox名称在列表中,避免因名称错误导致的选择失败。 - 所有IMAP命令的返回值都建议做检查,能快速定位问题所在。
内容的提问来源于stack exchange,提问作者relu
相关产品推荐
相关产品推荐

