未定义 Firebase Cloud 函数 mailTransport

Firebase Cloud function mailTransport is not defined

我正在尝试实现一个功能,如果有数据写入我的 firebase 实时数据库,该功能将向我发送电子邮件。但是,由于错误指出 "mailTransport is not defined"(见下文),

,电子邮件永远不会发送

这是我从 Whosebug 上的另一个 post 获得的代码。

 // Function to send email 
 exports.sendTestEmail = functions.database.ref('/messages')
 .onWrite(event => {
    return sendTestEmail('testemail@gmail.com');
  })

// Sends a notification to me
function sendTestEmail(email) {

   const mailOptions = {
      from: `someone`,
      to: email
   };

   mailOptions.subject = `Welcome!`;
   mailOptions.text = `Hey there! Here is the email notification`;

   return mailTransport.sendMail(mailOptions).then(() => {
    console.log('New message sent!);
    return
   });
}

不过,我认为这段代码是正确的,问题是无法识别mailTransport。我确实通过终端安装了 nodemailer,但这没有任何区别。所以,简而言之,我怎样才能让我的代码识别 mailTransport?

这是错误的日志报告:

 ReferenceError: mailTransport is not defined 
 at sendTestEmail (/user_code/index.js:32:10)
 at exports.sendTestEmail.functions.database.ref.onWrite.event (/user_code/index.js:16:12)
 at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
 at next (native)
 at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
 at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
 at /var/tmp/worker/worker.js:695:26
 at process._tickDomainCallback (internal/process/next_tick.js:135:7)

非常感谢!

您似乎忘记将 nodemailer 导入到您的脚本中。在 index.js 的顶部添加

const nodemailer = require('nodemailer');

请注意,我是从 https://nodemailer.com/about/#example 上的第一个 nodemailer 样本中得到这个的,所以如果你有问题,我建议你花一些时间在那里。