Monday, 3 April 2017

Firebase Cloud Function Email Duplicates

Im trying to implement some code that sends an email to anyone who would like to sign up to my newsletter. The code is actually working, but it sends multiple duplicates. Im using Firebase' samplecode, like this.

I think the problem is that it listensens for every change on the {uid} and I'm setting 4 values. If I manually change anything at the database from the dashboard, it triggers the event and sends a new mail. My code:

'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);
    });
  }
});



via Jaafar Mahdi

No comments:

Post a Comment