当Firebase数据库获取新数据时发送电子邮件

时间:2018-10-09 12:21:43

标签: reactjs firebase firebase-realtime-database google-cloud-functions

我是FireJS的NodeJS和Cloud Functions的新手,我的网站(内置ReactJS)已连接到Firebase实时数据库-当客户订购产品时,他在html输入中编写的所有数据都存储在Firebase数据库中。

现在,我要自动发送包含该数据的电子邮件。

来自:test@mail.com 主旨:为您准备的新订单

名称:“ Bla bla” 产品:“ Blaa”

你明白了。

我以为Firebase的Cloud Functions是答案,有人可以帮助我吗?我应该在functions / index.js中实现什么代码?

编辑:这是我数据库中的JSON数据:

{
  "Email_Message" : {
    "-LOOFLA-OFkKY_6Ut03b" : {
      "email" : "",
      "message" : "",
      "name" : ""
    }
  }
}

1 个答案:

答案 0 :(得分:1)

在“ Firebase示例库的云功能”中查看此官方示例:https://github.com/firebase/functions-samples/tree/Node-8/email-confirmation

在此示例中,每次在/users主节点下写入(并修改)新节点时,都会触发Cloud Function。您应该使此路径适应您自己的数据结构。

还请注意,示例中使用的事件处理程序为onWrite(),“它将在实时数据库中创建,更新或删除数据时触发”。如果您只想在创建订单时触发电子邮件发送,则可以使用onCreate()处理程序,请参阅文档:https://firebase.google.com/docs/functions/database-events


更新,基于您对数据库结构的更新。

根据您的结构,您应该修改Cloud Function示例代码,如下所示:

'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 = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword,
  },
});

exports.sendEmailConfirmation = functions.database.ref('/Email_Message/{mailId}').onWrite(async (change) => {
  const snapshot = change.after;
  const val = snapshot.val();

  const mailOptions = {
    from: '"......" <youremail@xxxxxxxxx.com>',
    to: val.email,
  };

  // Building Email message.
  mailOptions.subject = 'Dear ' + val.name;  //for example
  mailOptions.text = val.message;

  try {
    await mailTransport.sendMail(mailOptions);
    console.log('email sent to:', val.email);
  } catch(error) {
    console.error('There was an error while sending the email:', error);
  }
  return null;
});
相关问题