使用Python访问Gmail邮件时出现AUTHENTICATIONFAILED认证失败如何解决
你收到的[AUTHENTICATIONFAILED] Invalid credentials (Failure)报错是谷歌账号安全策略限制导致的:2022年5月30日起,谷歌不再支持第三方应用直接使用谷歌账号原始密码通过IMAP等协议登录访问邮箱,普通密码登录请求会被直接拦截。
修复方案
方案一:使用应用专用密码(操作最简单,适合个人测试使用)
使用前提:你的谷歌账号已开启两步验证功能
- 进入谷歌账号「安全性」设置页面
- 在「登录谷歌」分类下确认两步验证已成功开启
- 找到同分类下的「应用专用密码」入口,点击进入
- 应用类型选择自定义,填写任意标识名称(比如Python邮件工具),点击生成
- 将生成的16位无空格专用密码,替换你代码中
password变量的原有值即可,无需修改其他代码逻辑
注意:应用专用密码仅生成时展示一次,丢失后可回到该页面重新生成新密码即可
方案二:使用OAuth2认证(安全性更高,适合正式场景使用)
如果不希望开启两步验证,或者需要更规范的应用接入方式,可以将原有密码登录逻辑替换为OAuth2认证登录,操作如下:
- 前往谷歌云控制台创建新项目,搜索并启用Gmail API
- 配置OAuth同意屏幕,生成桌面应用类型的客户端凭证,保存为
credentials.json文件到代码同级目录 - 安装所需依赖:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
- 替换原有登录部分的代码为以下逻辑:
import imaplib import os from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # 你的Gmail邮箱地址 username = "你的邮箱地址@gmail.com" SCOPES = ['https://mail.google.com/'] def get_oauth2_credentials(): creds = None # 已生成的token文件会直接读取,无需每次授权 if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # 凭证过期或不存在时重新授权 if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server(port=0) # 保存凭证到本地,下次运行直接使用 with open('token.json', 'w') as token: token.write(creds.to_json()) return creds creds = get_oauth2_credentials() # 替换原有登录逻辑 imap = imaplib.IMAP4_SSL("imap.gmail.com") imap.authenticate('XOAUTH2', lambda x: f'user={username}\1auth=Bearer {creds.token}\1\1'.encode('ascii')) # 后续读取邮件的逻辑和原有代码完全一致
内容的提问来源于stack exchange,提问作者Moussa L
相关产品推荐
相关产品推荐

