【问题标题】:Cloud Function for Firebase: Email DuplicatesFirebase 的云功能:电子邮件重复
【发布时间】:2017-04-03 18:49:44
【问题描述】:

我正在尝试实现一些代码,该代码可以向任何想要订阅我的时事通讯的人发送电子邮件。该代码实际上是有效的,但它发送了多个重复项。我正在使用 Firebase 的示例代码,就像这样。

我认为问题在于它会监听 {uid} 上的每个更改,并且我设置了 4 个值。如果我从仪表板手动更改数据库中的任何内容,它会触发事件并发送新邮件。我的代码:

'use strict';

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

// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.

const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
    `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);

// Sends an email confirmation when a user changes his mailing list subscription.
exports.sendEmailConfirmation = functions.database.ref('/mailingList/{uid}').onWrite(event => {
  const snapshot = event.data;
  const val = snapshot.val();

  if (!snapshot.changed('subscribed')) {
    return;
  }

  const mailOptions = {
    from: '"Spammy Corp." <noreply@firebase.com>',
    to: val.email
  };

  // The user just subscribed to our newsletter.
  if (val.subscribed == true) {
      mailOptions.subject = 'Thanks and Welcome!';
      mailOptions.text = 'Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.';
      return mailTransport.sendMail(mailOptions).then(() => {
        console.log('New subscription confirmation email sent to:', val.email);
    });
  }
});

【问题讨论】:

    标签: node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    数据库触发器将针对其监控的路径所做的每一次更改运行,您需要为此做好计划。在您的函数中,您需要一种方法来确定电子邮件是否已发送。典型的解决方案是将布尔值或其他一些标志值写回触发更改的节点,然后每次检查该值,如果已设置则提前返回。

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 2018-12-19
      • 2017-12-03
      • 2020-11-22
      • 2019-01-16
      • 1970-01-01
      • 2021-06-18
      • 2019-07-23
      • 2020-04-23
      相关资源
      最近更新 更多