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

使用Python imaplib访问Gmail时认证失败问题求助

解决Gmail IMAP认证失败(AUTHENTICATIONFAILED)的可行方案

由于谷歌已关闭第三方应用的低安全访问权限,直接用账号密码登录IMAP会触发认证失败,以下是两种当前有效的解决方案:

方法一:应用专用密码(需开启两步验证)

仅适用于已开启谷歌账号两步验证的情况:

  • 操作步骤:
    1. 登录谷歌账号,进入「安全性」设置页面
    2. 确认「两步验证」已开启,若未开启需先完成设置
    3. 在「两步验证」模块下方找到「应用专用密码」,点击「创建」
    4. 输入自定义标识名称(如「Python邮件脚本」),点击「生成」
    5. 复制生成的16位无空格密码,替换代码中的密码字段
  • 修改后的代码:
import imaplib
import email

username = 'myemail@gmail.com'
# 替换为生成的16位应用专用密码
password = '你的应用专用密码'

mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(username, password)

方法二:OAuth2认证(通用方案)

无需应用专用密码,适用于所有谷歌账号,安全性更高:

  • 操作步骤:
    1. 登录谷歌云平台,创建新项目
    2. 在项目中搜索并启用「Gmail API」
    3. 进入「API和服务」→「凭据」,点击「创建凭据」→「OAuth客户端ID」
    4. 应用类型选择「桌面应用」,输入名称后创建,下载「credentials.json」到脚本目录
    5. 安装依赖包:pip install google-auth google-auth-oauthlib google-auth-httplib2
  • 示例代码:
import imaplib
import os.path
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# 定义Gmail API权限范围
SCOPES = ['https://mail.google.com/']
username = 'myemail@gmail.com'

def get_credentials():
    creds = None
    # 读取已保存的凭据(若存在)
    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

# 获取OAuth2凭据并构建认证字符串
creds = get_credentials()
auth_string = f'user={username}\1auth=Bearer {creds.token}\1\1'

# 连接IMAP服务器并完成OAuth2认证
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.authenticate('XOAUTH2', lambda x: auth_string)

额外注意事项

  • 无论使用哪种方法,需确保Gmail的IMAP功能已开启:进入Gmail设置→「转发和POP/IMAP」→「IMAP访问」选择「启用IMAP」
  • OAuth2认证首次运行会弹出浏览器,需登录谷歌账号完成授权,后续将自动使用保存的token.json

内容的提问来源于stack exchange,提问作者Albert Lungu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 17:50:10