且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Firebase函数中使用gmail时出现Nodemailer错误

更新时间:2022-04-30 10:05:42

在后台触发的Cloud Function中执行异步操作时,您必须返回一个promise,以这种方式Cloud Function等待该promise依次解决终止.

When you execute an asynchronous operation in a background triggered Cloud Function, you must return a promise, in such a way the Cloud Function waits that this promise resolves in order to terminate.

在以下官方Firebase视频系列中对此有很好的解释: https://firebase.google.com/docs/functions/video-series/.尤其要观看标题为学习JavaScript承诺"的三个视频(第2和第3部分特别关注后台触发的Cloud Functions,但之前确实值得观看第1部分).

This is very well explained in the official Firebase video series here: https://firebase.google.com/docs/functions/video-series/. In particular watch the three videos titled "Learn JavaScript Promises" (Parts 2 & 3 especially focus on background triggered Cloud Functions, but it really worth watching Part 1 before).

因此,您应该按照以下步骤修改代码:

So you should modify your code as follows:

exports.sendEmails = functions.database.ref('/users/{userID}/credentials').onCreate((snap, context) => {

  const userID = context.params.userID;
  const vals = snap.val()

  userName = vals.name;
  emailRecepient = vals.email;

  return smtpTransport.sendMail(mailOptions);
});

如果要将电子邮件发送结果打印到控制台,可以执行以下操作:

If you want to print to the console the result of the email sending, you can do as follows:

  return smtpTransport.sendMail(mailOptions)
    .then((info) => console.log('Email sent: ' + info.response))
    .catch((error) => console.log("Error sending email ---- ", error));
});


实际上,有一个正式的Cloud Functions示例可以做到这一点,请参阅 https://github.com/firebase/functions-samples/blob/master/email-confirmation/functions/index.js