简体   繁体   中英

Send data from Realtime Database using Firebase Functions to email

How to send certain data via email to Firebase Functions? Let's say there is an authorized user and some of his data (eg date of birth) we put in the Realtime Database. How, using Firebase Functions, do you send this field to email after HTTP request?

To send an email via JS, you need to connect nodemailer

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

and create transport:

let mailTransportAuth = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false,
    requireTLS: true,
    auth: {
        user: 'email',  /
        pass: 'password'
    }
});

Then create a function that will monitor the changes (onUpdate) in Realtime database and send letters:

exports.sendCodeOnEmail = functions.database.ref('/users/{userssId}/').onUpdate((snapshot, context) => {
    var newCode = generateCode()
    var key = Object.keys(snapshot.after.val())[0];

    const c = snapshot.after.child(key).toJSON().toString();
    const email = snapshot.after.child("email").exportVal();
    const code = snapshot.after.child("code").exportVal();

        snapshot.after.ref.update({'code': newCode});
        const mailOptions = {
            from: '"From me" <noreply@firebase.com>',
            to: email,
            text: "text"
        };
        mailOptions.subject = "Subject message";
        console.log(snapshot);

        try {
            mailTransportAuth.sendMail(mailOptions);
            console.log(`Email sent to:`, email);
        } catch (error) {
            console.error('There was an error while sending the email:', error);
        }

    console.log("Send code on email: " + email, " , code: " + code);

    return null;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM