Firebase functions with nodemailer POST request: Error: Process exited with code 16

Firebase functions with nodemailer POST request: Error: Process exited with code 16

我正在 运行 构建一个 Firebase 云函数,其目的是处理“联系我”表单的后端。 Express 框架用于中间件功能。单击提交按钮后,将向 /submit 端点发出 POST 请求。

functions文件夹下的

index.js如下:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const bodyParser = require("body-parser");
const express = require("express");
const emailRoute = require("./routes/email");

// Initialize Firebase in order to access its services.
admin.initializeApp();

const app = express();

// Automatically allow cross-origin requests.
app.use(cors({ origin: true }));

app.use(bodyParser.urlencoded({extended: false}));

app.use(emailRoute);

// Expose Express API as a single Cloud Function.
exports.app = functions.https.onRequest(app);

email.js导入的路由器如下:

const nodemailer = require("nodemailer");
const express = require("express");
const router = express.Router();

router.post("/submit", (req, res) => {
  
  const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: "email@gmail.com",
      pass: "password",
    },
  });

  const myEmail = {
    to: "myemail@gmail.com",
    subject: `A new message from ${req.body.name}`,
    text: `${req.body.name} sent the following message:
          \n\n ${req.body.message}
          \n\n Senders email: ${req.body.email}`,
  };

  const sendersEmail = {
    to: req.body.email,
    subject: "A copy of your message to me",
    text: `You just sent me the following message:\n\n${req.body.message}`,
  };

  console.log("SUBMIT REQUEST PROCESSING");

  transporter.sendMail(myEmail);
  transporter.sendMail(sendersEmail);

  res.redirect("/#contact");

  console.log("PROCESSING COMPLETE");
});

module.exports = router;

在本地环境中 运行 没有问题 - 电子邮件会发送给双方。但是,当 运行 在托管环境中作为 Firebase 函数时,会抛出以下错误:Error: Process exited with code 16(如 Firebase 控制台的函数日志部分所示)。之前的 SO 表示 uncaughtExceptionunhandledRejection.

在错误之前,记录了两个 console.log() 语句。然后该函数以 302 状态代码结束(就像在 运行 本地成功时所做的那样)。在那之后,我的 Google 帐户收到未处理的拒绝,然后是 Error: Invalid login 和 link 以及一条声明“请通过您的网络浏览器登录,然后重试”。

这可能是针对 nodemailer 试图执行的自动邮件的 Firebase 安全措施吗?

问题出在登录您的 Google 帐户时。您是否在 Google 帐户中启用了安全性较低的应用程序?或者更好的是,我建议使用其他一些身份验证,如下所述: https://support.google.com/a/answer/176600?hl=en

我需要在 gmail 帐户上同时启用 less secure apps and display unlock captcha,我之前只启用了前者。

我还需要设置 gmail.emailgmail.password Google 云环境变量。这可以通过以下 shell 命令完成:firebase functions:config:set gmail.email="myusername@gmail.com" gmail.password="secretpassword"

我在其中找到的一个很好的资源是 official Firebase function sample,它利用了 Nodemailer,其中涵盖了上述内容。