0
我試圖執行一些代碼,發送電子郵件給任何想要註冊我的通訊的人。代碼實際上正在工作,但它會發送多個副本。我使用Firebase的樣本代碼,就像這樣。Firebase的雲端功能:電子郵件重複
我認爲問題是,它listensens有關{} 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." <[email protected]>',
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);
});
}
});