【问题标题】:Angular 8/Nodemailer - Contact Form function not logging errors, no email receivedAngular 8/Nodemailer - 联系表单功能未记录错误,未收到电子邮件
【发布时间】:2020-05-21 17:31:57
【问题描述】:

我正在使用 Angular 8/Firebase 堆栈,并且我有一个联系表单,可以写入我的 Firestore 集合。这工作正常。我还编写了一个云函数,它在写入数据库时​​触发并将 nodemailer 电子邮件发送到我的个人电子邮件。

问题是我从来没有收到任何电子邮件,即使每次我提交测试联系表时云功能记录器似乎都会关闭。没有记录错误,但我的 console.logs 也没有记录。

我在用来发送电子邮件的 Gmail 上允许使用不太安全的应用并禁用验证码(即使我不使用 2FA)。依然没有。现在,我不知道会发生什么,因为我没有可使用的日志。

这是我的云函数 index.js:

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

const admin = require('firebase-admin');
admin.initializeApp();
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
  smtpTransport({
    service: 'gmail',
    auth: {
      user: `${gmailEmail}`,
      pass: `${gmailPassword}`
    }
  })
);

exports.sendContactMessage = functions.database
  .ref('/messages/{pushKey}')
  .onWrite(event => {
    const snapshot = event.data;
    if (snapshot.previous.val() || !snapshot.val().name) {
      return;
    }

    const val = snapshot.val();

    const mailOptions = {
      from: `${gmailEmail}`,
      to: 'donotreply@something.com',
      subject: `You've been contacted by ${val.name} ✨`,
      text: `${val.message}`
    };
    return mailTransport.sendMail(mailOptions, (error, info) => {
      if (error) {
        console.log('Error occurred');
        console.log(error.message);
      }
    });
  });

触发器本身似乎正在工作,因为每次我在联系表单上点击提交时,我都会在控制台中看到 Firebase 日志(但不是 console.logs)。我认为这是 SMTP 或我的 mailTransport 对象的问题。我已经为这个对象尝试了很多不同的格式,我在网上找到了这些格式,但都没有。

注意:我通过 Firebase CLI 设置的 Gmail 和密码的字符串插值变量,当我运行命令检索它们时它们会正确记录。这不是凭据问题。

【问题讨论】:

  • 您确定没有将实时数据库的 Cloud Function 触发器与 Firestore 的触发器混为一谈。它们是 Firebase 提供的两种不同的 NoSQL 数据库服务。 exports.sendContactMessage = functions.database .ref('/messages/{pushKey}') .onWrite(...) 用于声明实时数据库的触发器,但您表明您写入 Firestore。
  • 有趣,可能就是这样。但如果是,为什么写入我的 Firestore 会触发云功能并输出日志?
  • 我也有同样的问题! :-) 但是您是否确认您使用的是 Firestore(带有集合和文档)而不是实时数据库?
  • 您只声明了一个云函数。你能确认一下吗?
  • 是的。我刚刚将代码更改为functions.firestore.document('messages/{pushKey}').onCreate((snap, context) => {}),它现在可以正常记录错误了!谢谢!请添加您的建议作为答案,以便我投票,您可以获得代表!

标签: javascript angular firebase google-cloud-functions


【解决方案1】:

显然,您将 Realtime Database 的 Cloud Function 触发器与 Firestore 的触发器混淆了。它们是 Firebase 提供的两种不同的 NoSQL 数据库服务。

exports.sendContactMessage = functions.database
  .ref('/messages/{pushKey}')
  .onWrite(...)

用于声明实时数据库的触发器,但您在问题中指出您写入 Firestore。

所以你必须改变你的函数声明如下:

exports.sendContactMessage = functions.firestore
   .document('messages/{pushKey}')
   .onCreate((snap, context) => {...})

【讨论】:

    猜你喜欢
    • 2019-06-02
    • 2017-05-27
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多