首页 > 解决方案 > 如何在 firebase 数据库中检索用户输入值,然后向我发送电子邮件?

问题描述

我在 firebase 上托管我的网站。我还将这个 js 文件部署到了 firebase 云函数。

我如何对其进行编码,以便用户在我的网站上的联系表单上输入内容后,该代码将检索数据库中的用户输入值,然后向我发送电子邮件?

更新:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');

admin.initializeApp();

exports.sendEmailConfirmation = functions.database.ref("/contactData")
    .onCreate((snapshot, context) => {

        let transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
                user: "myemail@gmail.com",
                pass: "mypassword"
            }
        });

        // Grab the current value of what was written to the Realtime Database.
        const original = snapshot.val();

        console.log('sending email');
        console.log(original);

        const mailOptions = {
            from: val.email,
            to: 'myemail@gmail.com',
        };

        mailOptions.subject = val.name + "  \n " + val.subject;
        mailOptions.text = val.message;

        console.log('Created entry', context.params.pushId, original);
        // You must return a Promise when performing asynchronous tasks inside a Functions
        // Your code ...
        return transporter.sendMail(mailOptions, function (err, data) {
            if (err) {
                console.log('error occurs!');
            } else {
                console.log('email sent!');
            }
        });
    });

标签: javascriptfirebasewebfirebase-realtime-databasegoogle-cloud-functions

解决方案


我会使用onCreate来自实时数据库的。从问题不清楚是什么goMail。但是,您应该在 Firebase 函数中返回一个值或一个承诺。 关联

exports.sendEmailConfirmation = functions.database.ref('Email_Message/{mailId}')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const original = snapshot.val();
      console.log('Created entry', context.params.pushId, original);
      // You must return a Promise when performing asynchronous tasks inside a Functions
      // Your code ...
      return mailTransport.sendMail(mailOptions);
  });

推荐阅读