使用Nodemailer连接Gmail出现self-signed certificate in certificate chain错误
使用Nodemailer发送Gmail邮件时遇到“self-signed certificate in certificate chain”错误
我在使用Nodemailer向Gmail账户发送邮件时,遇到了“self-signed certificate in certificate chain”错误。此前该代码运行正常,且已确认Gmail服务器配置、两步验证密码及收件人信息均正确。
这是Gmail服务器,我的两步验证密码正确,收件人信息也没问题
相关代码
"use strict"; const nodemailer = require("nodemailer"); // async..await is not allowed in global scope, must use a wrapper async function main() { // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", //Gmail服务器 port: 465, //Gmail服务器端口 secure: true, //true对应465端口,其他端口设为false auth: { user: '****@gmail.com', pass: 'qskafnvgyhzyrceb' //应用专用密码 }, }); // send mail with defined transport object let info = await transporter.sendMail({ from: '*****@gmail.com', // 发件人地址 to: '*****@gmail.com', // 收件人列表 subject: "Hello ✔", // 邮件主题 text: "Hello world?", // 纯文本内容 html: "<h1>Hello World</h1>", // HTML内容 }); } main().then(() => { console.log('邮件已发送') }).catch((err)=>{ console.log(err) });
错误堆栈信息
Error: self-signed certificate in certificate chain at TLSSocket.onConnectSecure (node:_tls_wrap:1538:34) at TLSSocket.emit (node:events:513:28) at TLSSocket._finishInit (node:_tls_wrap:952:8) at ssl.onhandshakedone (node:_tls_wrap:733:12) { code: 'ESOCKET', command: 'CONN' }
解决方案
1. 临时跳过证书验证(仅测试环境使用)
在创建transporter时添加tls.rejectUnauthorized: false配置,强制跳过SSL证书验证:
let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 465, secure: true, auth: { user: '你的邮箱@gmail.com', pass: '你的应用专用密码' }, tls: { // 跳过证书验证,生产环境不建议使用 rejectUnauthorized: false } });
2. 生产环境推荐方案:更新本地CA证书
该错误本质是Node.js环境缺少可信的根证书,无法验证Gmail的SSL证书链。可以通过以下方式解决:
- 下载Mozilla维护的最新根证书包
- 设置环境变量
NODE_EXTRA_CA_CERTS指向证书文件路径,或者在transporter的tls.ca选项中直接传入证书内容,确保Node.js能识别Gmail的证书链。
内容的提问来源于stack exchange,提问作者Joalop
相关产品推荐
相关产品推荐

