NodeJS 如何在Firebase真实的数据库中创建新密钥时收到电子邮件

7hiiyaii  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(87)

好吧,我几乎到处都找过了,显然有Firebase云功能,每当我的数据库中创建了一个新的密钥时,它可以用来向我发送电子邮件。但是,我不能把我的头缠在哪里开始和如何做。有人能帮助我吗?

svmlkihl

svmlkihl1#

您确实可以使用云函数在每次数据库中创建新节点(即新键)时发送电子邮件。
请查看实时数据库触发器here的文档,以及其中一个官方云函数示例,该示例显示了如何发送电子邮件here
在示例中,发送电子邮件以响应用户帐户的创建和删除,但是将示例代码与RealtimeDatabase触发器集成起来并不困难。
例如,您可以执行类似以下的操作,这些操作改编自示例:

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For Gmail, enable these:
// 1. https://www.google.com/settings/security/lesssecureapps
// 2. https://accounts.google.com/DisplayUnlockCaptcha
// 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 = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword,
  },
});

// Your company name to include in the emails
// TODO: Change this to your app or company name to customize the email sent.
const APP_NAME = 'xxxxxx';

exports.sendWelcomeEmail = functions.database.ref('/thePathYouWant/{pushId}')
    .onCreate((snapshot, context) => {

       const createdData = snapshot.val(); // data that was created

       const email = createdData.email; // The email of the user. We make the assumption that it is written at the new database node
       const displayName = createdData.displayName; // The display name of the user.

       return sendWelcomeEmail(email, displayName);
});

// Sends a welcome email to the given user.
async function sendWelcomeEmail(email, displayName) {
  const mailOptions = {
    from: `${APP_NAME} <noreply@firebase.com>`,
    to: email,
  };

  // The user subscribed to the newsletter.
  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Hey ${displayName || ''}! Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
  await mailTransport.sendMail(mailOptions);
  return console.log('New welcome email sent to:', email);
}

如果您对Firebase的Cloud Functions完全陌生,那么按照教程here并观看官方视频系列here可能是个好主意。

相关问题