You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用imap-tools库登录时出现“LOGIN failed”错误求助

解决imap-tools登录Office365时的"LOGIN failed"错误

针对你遇到的预期响应状态为"OK",但收到"NO"。数据:[b'LOGIN failed.']登录失败问题,可按以下步骤排查解决:

  • 确认账号密码有效性

    • 确保login变量是完整的邮箱地址(如xxx@outlook.com或企业域邮箱xxx@yourcompany.com)
    • 验证密码是否正确,若包含特殊字符,直接使用明文测试排除转义问题
  • 启用IMAP协议

    • 登录Outlook网页版,进入「设置」→「邮件」→「同步电子邮件」,确认IMAP功能已开启
    • 企业版Office365需联系管理员,在Exchange后台为账号开启IMAP访问权限
  • 应用密码替代普通密码(两步验证账号)

    • 若账号开启了两步验证,普通密码无法用于IMAP登录,需生成应用专用密码:
      1. 登录微软账号安全中心
      2. 找到「应用密码」选项,生成专属密码
      3. 将代码中的password替换为该应用密码
  • 修正服务器连接配置

    • Office365的IMAP服务要求SSL加密,端口为993,需调整代码中的MailBox初始化:
      MailBox('outlook.office365.com', port=993).login(login, password)
      
      或直接使用MailBoxTLS类简化配置:
      from imap_tools import MailBoxTLS
      with MailBoxTLS('outlook.office365.com').login(login, password) as mailbox:
          # 后续逻辑
      
  • 代码其他潜在问题修正

    • 补充缺失的datetime、timedelta导入语句
    • 闭合未完成的try块,避免语法错误
    • 使用imap-tools原生的AND参数格式(如AND(since=datetime.date(2022,6,22)))替代字符串,提升兼容性

修正后的完整示例代码:

from imap_tools import MailBox, AND
from datetime import datetime, timedelta
import chardet

login = "your_full_email@outlook.com"
password = "your_password_or_app_password"

with MailBox('outlook.office365.com', port=993).login(login, password) as mailbox:
    data_anterior = (datetime.today() - timedelta(days=1)).strftime("%d-%b-%Y")
    for msg in mailbox.fetch(AND(since=datetime.date(2022, 6, 22))):
        message_ID = msg.headers.get('message-id', 'N/A')
        try:
            for att in msg.attachments:
                if '.xml' in att.filename.lower():
                    get_encoding = chardet.detect(att.payload)
                    payload = str(att.payload, get_encoding['encoding']).upper()
                    # 添加你的XML处理逻辑
        except Exception as e:
            print(f"处理附件出错: {str(e)}")

内容的提问来源于stack exchange,提问作者Murilo Maschke Ferreira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:24:56