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

未启用两步验证时,Gmail无法发送邮件的解决方法

解决Gmail SMTP 535认证错误(无需两步验证)

错误原因

Google已彻底移除「允许低安全性应用」功能,普通Gmail账号无法再通过明文密码完成SMTP认证。若不想启用两步验证,唯一可行的方案是使用OAuth2认证协议。

实现步骤

  1. 安装依赖库
    执行以下命令安装Google OAuth2相关工具:
pip install google-auth google-auth-oauthlib google-auth-httplib2
  1. 获取OAuth2凭据
  • 登录Google Cloud Console,创建新项目
  • 在项目中启用「Gmail API」
  • 创建「OAuth客户端ID」,应用类型选择「桌面应用」,下载凭据JSON文件并命名为credentials.json,放在代码同目录下
  1. 修改后的Python代码
import smtplib
from email.mime.text import MIMEText
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://www.googleapis.com/auth/gmail.send']

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

def send_email():
    creds = get_credentials()
    # 创建SMTP连接
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    # 使用OAuth2认证
    server.ehlo()
    server.login(creds.username, creds.token, initial_response_ok=True)
    
    # 构造邮件内容
    msg = MIMEText('hello')
    msg['Subject'] = 'Test Email'
    msg['From'] = 'mail_from@gmail.com'
    msg['To'] = 'mail_to@gmail.com'
    
    # 发送邮件
    server.send_message(msg)
    server.quit()

if __name__ == '__main__':
    send_email()

补充说明

  • 首次运行代码时会弹出浏览器窗口,要求你登录Gmail账号并授权该应用发送邮件
  • 授权成功后会生成token.json文件,后续运行无需再次授权
  • 若使用Google Workspace(原G Suite)账号,可联系管理员在后台开启「允许SMTP密码登录」选项,这样就能继续使用原密码认证方式(仅适用于Workspace账号,普通Gmail账号不可用)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:46:06