谷歌新政策下如何使用Nodemailer?认证报错求助
解决Nodemailer对接Gmail的认证错误问题
谷歌在2022年5月30日移除了“不太安全的应用访问”选项,原有的认证方式已失效,你可以通过以下两种方案解决这个问题:
方案一:使用App Password(仅支持开启两步验证的账号)
- 登录谷歌账号后进入安全性设置界面
- 找到App Passwords选项(仅开启两步验证后可见)
- 选择应用类型为“邮件”,设备选“其他(自定义名称)”,生成16位的App Password
- 将Nodemailer配置中的原账号密码替换为这个生成的密码,示例代码:
const nodemailer = require('nodemailer'); async function sendMail() { let transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'your-email@gmail.com', pass: '生成的16位App Password' } }); let info = await transporter.sendMail({ from: 'your-email@gmail.com', to: 'recipient@example.com', subject: '测试邮件', text: '这是通过App Password发送的测试邮件' }); console.log('邮件发送成功:', info.messageId); } sendMail().catch(console.error);
方案二:使用OAuth2认证(推荐,支持所有账号)
- 前往谷歌云平台创建项目并启用Gmail API
- 创建OAuth 2.0客户端ID,配置授权回调地址(本地测试可填
http://localhost:3000) - 获取客户端ID、客户端密钥和刷新令牌
- Nodemailer配置示例:
const nodemailer = require('nodemailer'); const { google } = require('googleapis'); const OAuth2 = google.auth.OAuth2; const oauth2Client = new OAuth2( '你的客户端ID', '你的客户端密钥', 'http://localhost:3000' // 回调地址 ); oauth2Client.setCredentials({ refresh_token: '你的刷新令牌' }); async function sendMail() { const accessToken = await oauth2Client.getAccessToken(); let transporter = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: 'your-email@gmail.com', clientId: '你的客户端ID', clientSecret: '你的客户端密钥', refreshToken: '你的刷新令牌', accessToken: accessToken } }); let info = await transporter.sendMail({ from: 'your-email@gmail.com', to: 'recipient@example.com', subject: '测试邮件', text: '这是通过OAuth2发送的测试邮件' }); console.log('邮件发送成功:', info.messageId); } sendMail().catch(console.error);
注意:使用OAuth2时,需确保谷歌账号已授权该客户端ID访问Gmail API,首次运行可能需要手动授权以获取刷新令牌。
内容的提问来源于stack exchange,提问作者Klackters
相关产品推荐
相关产品推荐

