You need to enable JavaScript to run this app. Django使用Gmail OAuth2发邮件遇「用户名密码不被接受」问题
优惠活动
大模型
产品
解决方案
定价
更多

Django使用Gmail OAuth2发邮件遇「用户名密码不被接受」问题

Django发送Gmail邮件两种方式均失败的问题

我在Django中尝试发送邮件,两种方式均失败:

  • 使用应用密码时无任何报错,但邮件从未送达,发件人邮箱也无发送记录;
  • 使用OAuth2方式(借助ChatGPT完成配置):已生成包含刷新令牌的配置文件,也编写了自定义后端,但发送邮件时提示「Username and Password not accepted」。

令牌文件内容

{
    "token": "[secret]",
    "refresh_token": "[secret]",
    "token_uri": "https://oauth2.googleapis.com/token",
    "client_id": "[secret]",
    "client_secret": "[secret]",
    "scopes": ["https://www.googleapis.com/auth/gmail.send"],
    "universe_domain": "googleapis.com",
    "account": "",
    "expiry": "2025-01-05T07:39:06.980351Z"
}

自定义后端代码

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from django.core.mail.backends.smtp import EmailBackend
from pathlib import Path
import os

class GmailOAuth2Backend(EmailBackend):
    def _get_access_token(self):
        dir = Path(__file__).resolve().parent
        file = os.path.join(dir, 'oauth2tokenfile.secret.json')
        creds = Credentials.from_authorized_user_file(file)
        if creds.expired and creds.refresh_token:
            creds.refresh(Request())
        return creds.token

    def open(self):
        self.password = self._get_access_token()
        #EDIT: 这里应该写成 "return super().open()"
        #这个修改对应用密码有效,但对OAuth无效。
        super().open()

Django配置

EMAIL_BACKEND = "[secret].GmailOAuth2Backend"
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[my email]@gmail.com'

调试显示:刷新令牌后,creds.valid 的值为 True。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:08:15