使用Python读取Gmail收件箱时遭遇认证失败问题求助
解决Gmail IMAP认证失败(无需开启“不太安全的应用”权限)
针对你遇到的[AUTHENTICATIONFAILED] Invalid credentials错误,在不启用“不太安全的应用”权限的前提下,有以下两种可靠解决方案:
方案1:使用App密码(适用于开启两步验证的账号)
如果你的Google账号已经开启了两步验证(2FA),可以生成专门的App密码来替代登录密码:
- 登录Google账号安全设置,找到「App密码」选项(仅开启2FA后可见)
- 为你的Python脚本生成一个App密码(该密码仅显示一次,务必保存)
- 将脚本中的
your_email_password替换为这个生成的App密码
修改后的登录代码示例:
mail.login('your_email_address', 'your_generated_app_password')
方案2:使用OAuth2.0认证(官方推荐的安全方式)
Gmail现在优先推荐OAuth2.0进行认证,步骤如下:
- 安装依赖库:
pip install google-auth google-auth-oauthlib google-auth-httplib2
- 前往Google Cloud Console创建新项目,启用Gmail API,并创建桌面应用类型的OAuth客户端ID,下载
credentials.json文件到脚本目录 - 使用以下修改后的脚本进行连接:
import imaplib import email from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import os.path # 定义所需的Gmail权限 SCOPES = ['https://mail.google.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 # 获取认证凭证 creds = get_credentials() # 通过OAuth2.0连接IMAP服务器 mail = imaplib.IMAP4_SSL('imap.gmail.com') auth_string = 'user={}\1auth=Bearer {}\1\1'.format('your_email_address', creds.token) mail.authenticate('XOAUTH2', lambda x: auth_string) mail.select('inbox') # 邮件读取逻辑(优化了多部分邮件的内容提取) status, data = mail.search(None, 'ALL') for num in data[0].split(): status, data = mail.fetch(num, '(RFC822)') email_message = email.message_from_bytes(data[0][1]) print('From:', email_message['From']) print('Subject:', email_message['Subject']) print('Date:', email_message['Date']) # 处理多格式邮件(纯文本/HTML) if email_message.is_multipart(): body_content = '' for part in email_message.walk(): if part.get_content_type() == 'text/plain': body_content += part.get_payload(decode=True).decode() print('Body:', body_content) else: print('Body:', email_message.get_payload(decode=True).decode()) print() # 关闭连接 mail.close() mail.logout()
额外注意事项
- 确保邮箱地址输入无误,拼写错误也会导致认证失败
- App密码仅对开启两步验证的账号可用,未开启2FA的账号无法使用该方式
- OAuth2.0方式虽然配置步骤稍多,但安全性更高,符合Google的最新安全规范
内容的提问来源于stack exchange,提问作者Anwesh saha
相关产品推荐
相关产品推荐

