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

使用Azure OAuth结合Nodemailer发送邮件时认证失败问题排查

邮件OAuth2认证失败排查(535 5.7.3 Authentication unsuccessful)

微软已停止支持Basic认证,我正在将项目中的邮件认证方式改为OAuth2,Azure端配置已确认正常。可以正常获取access_token,但使用该Token发送邮件时出现认证失败错误。

相关代码

创建邮件传输器

const createEmailTransporter = async () => {

  const accessToken = await getAccessToken();

  return nodemailer.createTransport({
    host: config.EMAIL_HOST,
    port: config.EMAIL_PORT,
    secure: false,
    auth: {
      type: 'OAuth2',
      user: config.EMAIL_ADDRESS,
      clientId: config.EMAIL_CLIENT_ID,
      clientSecret: config.EMAIL_CLIENT_SECRET,
      accessToken: accessToken,

    },
  });
};

获取AccessToken方法

const getAccessToken = async () => {
  let data = qs.stringify({
    'client_id': config.EMAIL_CLIENT_ID,
    'scope': config.EMAIL_SCOPE,
    'client_secret': config.EMAIL_CLIENT_SECRET,
    'grant_type': config.EMAIL_GRANT_TYPE,
    'password': config.EMAIL_PASSWORD,
  });

  let axiosConfig = {
    method: 'post',
    maxBodyLength: Infinity,
    url: `https://login.microsoftonline.com/${config.EMAIL_TENANT_ID}/oauth2/v2.0/token`,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: data
  };

  try {
    const response = await axios.request(axiosConfig);
    return response.data.access_token;

  } catch (error) {
    console.error("❌ Error getting access token:", error.response?.data || error.message);
    throw new Error(`Error getting access token: ${error}`);
  }
};

报错信息

{ 
  "error": { 
    "code": "500",  
    "message": "EAUTH",  
    "target": "An error has occurred: Invalid login: 535 5.7.3 Authentication unsuccessful [VI1PR04CA0115.eurprd04.prod.outlook.com 2025-02-20T17:01:08.809Z 08DD4FC050A77D92]",    
    "@Common.numericSeverity": 4  
  }
}

可能的问题排查方向

  • SMTP服务参数错误:
    微软Office365的SMTP服务标准配置为:

    • host: 'smtp.office365.com'
    • port: 587
    • secure: false
    • 必须添加requireTLS: true(启用TLS加密)
      若使用公司内部Exchange服务器,需确认该服务器是否支持OAuth2认证的SMTP接入。
  • Token权限或授权模式问题:

    • 确认scope是否包含https://outlook.office365.com/SMTP.Send(SMTP协议专用权限);
    • 密码授权模式(password grant)下,邮箱账号不能开启MFA,否则认证会失败,需切换为客户端凭证/授权码模式;
    • 解析Token检查scp字段是否包含SMTP.Send,aud字段是否为https://outlook.office365.com。
  • Nodemailer配置缺失:
    可尝试添加service: 'Outlook365'让nodemailer自动适配SMTP参数,同时确保access_token未过期(可在获取Token时记录expires_in,提前刷新)。

  • 账号或租户限制:

    • 确认邮箱账号可正常登录Outlook网页版并发送邮件;
    • 检查Azure AD中应用的权限是否已获得管理员批准(若为租户级权限);
    • 联系IT确认是否有安全策略禁止该账号通过第三方应用使用SMTP/OAuth2发送邮件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 06:16:17