【问题标题】:How to get an email when new key is created in Firebase real time database在 Firebase 实时数据库中创建新密钥时如何获取电子邮件
【发布时间】:2018-11-01 12:33:43
【问题描述】:

好吧,我几乎到处都看过,显然有 Firebase Cloud Functions 可以用来在我的数据库中创建新密钥时向我发送电子邮件。但是,我不知道从哪里开始以及如何做。谁能帮帮我。

【问题讨论】:

  • 您确定每次创建新节点时都需要一封电子邮件吗?这可能是很多封电子邮件。您的应用程序接收您感兴趣的节点的 childAdded 事件或者可能是通知不是更好吗?你能提供一个用例吗?有一个答案很可能是正确的,但应该考虑用例。
  • 起初我想要一封电子邮件,因为我知道不会创建很多密钥。

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


【解决方案1】:

您确实可以在每次在数据库中创建新节点(即新密钥)时使用云函数发送电子邮件。

查看实时数据库触发器here 的文档以及显示如何发送电子邮件的官方 Cloud Functions 示例之一here

在示例中,发送电子邮件以响应用户帐户的创建和删除,但将示例代码与实时数据库触发器集成起来并不难。

例如,您可以根据示例执行以下操作:

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

如果您完全不熟悉 Cloud Functions for Firebase,最好按照教程 here 并观看官方视频系列 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多