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

Firebase Cloud Functions中Nodemailer报PLAIN认证缺失错误的解决方法

解决Firebase Cloud Functions + Nodemailer Gmail认证错误:Missing credentials for "PLAIN"

这个错误我帮不少开发者排查过,核心原因基本都是Gmail的安全限制或者代码配置的小问题,咱们一步步来修复:

第一步:搞定Gmail的认证限制

哪怕你确认邮箱密码输入正确,Gmail现在也默认阻止非官方应用直接用账号密码登录。解决方法分两种情况:

  • 如果没启用两步验证:去Google账号的「安全」设置里开启「不太安全的应用访问」(不过这个选项现在很多账号已经被移除了,更推荐下面的方案)
  • 如果启用了两步验证(强烈推荐):在Google账号安全页找到「应用专用密码」,生成一个专门给Nodemailer用的密码——这个密码才是你要在代码里用的gmailPassword,不是你的普通邮箱登录密码。

第二步:别硬编码敏感信息,用Firebase环境变量

直接把邮箱和密码写在代码里不仅不安全,还可能因为特殊字符、编码问题导致读取失败。用Firebase CLI设置环境变量更稳妥:
打开终端运行这两个命令:

firebase functions:config:set gmail.email="your-email@gmail.com"
firebase functions:config:set gmail.password="your-app-specific-password"

之后在代码里通过functions.config()来读取这些值。

第三步:修正代码里的小问题

你的代码还有两个细节可能引发异常:

  1. 数据库实例名称里的空格:functions.database.instance('abc- in')里的空格会导致实例识别错误,改成正确的实例ID(比如abc-in)
  2. 旧版Functions SDK的event结构:如果用的是v1及以上版本,event.data已经被弃用,要改用snapshot参数直接获取数据

修改后的完整代码:

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');

// 从环境变量读取敏感配置
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const APP_NAME = 'ABC In';

// 初始化邮件传输器
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword // nodemailer支持pass或password两种写法
  }
});

// 监听数据库新增事件(修正实例名称和参数结构)
exports.salonCreatedAccount = functions.database.instance('abc-in').ref('/abc/{def}').onCreate((snapshot) => {
  const val = snapshot.val();
  console.log(val);
  
  const email = val.email;
  const displayName = val.name;
  
  return sendconfirmationEmail(email, displayName);
});

// 发送确认邮件函数
function sendconfirmationEmail(email, displayName){
  const mailOptions = {
    from: `${APP_NAME} <${gmailEmail}>`,
    to: email
  };
  
  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Hi ${displayName},\n\nWelcome to ${APP_NAME}! We're excited to have you on board.\n\nBest regards,\nThe ${APP_NAME} Team`;
  
  return mailTransport.sendMail(mailOptions)
    .then(() => {
      console.log(`New welcome mail sent to ${email}`);
      return null; // 确保函数返回resolved的Promise
    })
    .catch(error => {
      console.error('Error sending email:', error);
      return null;
    });
}

最后:重新部署函数

修改完代码后,记得重新部署生效:

firebase deploy --only functions

这样应该就能彻底解决认证错误了,核心是Gmail的应用专用密码和正确的配置读取方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:58:12