使用Python通过IMAP连接企业版Outlook服务器遇LOGIN failed错误求助
微软企业账户IMAP登录Outlook失败(b'LOGIN failed.')排查与解决
我拥有一个微软企业账户,想要使用Python通过IMAP协议连接Outlook服务器(端口993),运行代码后出现错误b'LOGIN failed.'。尝试过使用应用密码或关闭双重认证(2FA),但仍遇到该错误。
代码示例
import imaplib import email from email.header import decode_header import webbrowser import os import rds_config # account credentials username = "myname@enterprise.microsoft.com" password = "mypassword or app-password" imap_server = 'outlook.office365.com' # create an IMAP4 class with SSL imap = imaplib.IMAP4_SSL(imap_server, port=993) # authenticate imap.login(username, password) # status, messages = imap.select('"Sent Items"') status, messages = imap.select('INBOX') messages = int(messages[0])
报错信息
--------------------------------------------------------------------------- error Traceback (most recent call last) c:\Users\Among\Desktop\Code\UpWork\rodney_projects\lambda_sync_email_to_MYSQL\source\test.ipynb Cell 15 in <cell line: 26>() 24 imap = imaplib.IMAP4_SSL(imap_server, port=993) 25 # authenticate ---> 26 imap.login(username, password) 28 # status, messages = imap.select('"Sent Items"') 29 status, messages = imap.select('INBOX') File c:\Users\Among\AppData\Local\Programs\Python\Python39\lib\imaplib.py:612, in IMAP4.login(self, user, password) 610 typ, dat = self._simple_command('LOGIN', user, self._quote(password)) 611 if typ != 'OK': ---> 612 raise self.error(dat[-1]) 613 self.state = 'AUTH' 614 return typ, dat error: b'LOGIN failed.'
排查与解决方法
检查企业邮箱IMAP权限
微软企业账户(Office 365)的IMAP访问可能被管理员禁用。联系IT管理员确认:- 你的账户是否开启了IMAP协议访问权限
- 租户全局设置中是否禁用了IMAP服务
改用OAuth2认证
微软对企业账户的传统密码/应用密码登录限制逐渐严格,推荐使用OAuth2认证:- 在Azure AD中注册应用,获取客户端ID、客户端密钥及授权范围(需包含
IMAP.AccessAsUser.All) - 获取有效访问令牌后,通过XOAUTH2方式认证:
import imaplib username = "myname@enterprise.microsoft.com" access_token = "your_oauth2_access_token" imap_server = 'outlook.office365.com' imap = imaplib.IMAP4_SSL(imap_server, 993) auth_string = f"user={username}\x01auth=Bearer {access_token}\x01\x01" imap.authenticate('XOAUTH2', lambda x: auth_string) # 后续操作如选择收件箱 status, messages = imap.select('INBOX')- 在Azure AD中注册应用,获取客户端ID、客户端密钥及授权范围(需包含
确认账户状态
- 检查账户是否处于激活状态,未被管理员锁定
- 确认是否有安全策略限制了非信任设备/IP的登录请求
验证网络与服务器连通性
可以通过telnet outlook.office365.com 993测试端口是否可正常连通,排除网络防火墙或代理的干扰
内容的提问来源于stack exchange,提问作者Trần Tiến Văn
相关产品推荐
相关产品推荐

