0

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?

Dmitrii
  • 13
  • 1
  • Do you want to export all Realtime Database and send it to email? – NickUnuchek Feb 07 '19 at 12:39
  • @NickUnuchek, No, I want to send one-specific field (in this user's branch) – Dmitrii Feb 07 '19 at 13:15
  • 1
    As it stands now your question is a bit too broad. It reads like "here's my use-case, how can I do this?" That's not a good format for Stack Overflow, where we deal best with more concrete and focused problems. There are three complex technologies involved here: triggering a Cloud Function, reading from the database, sending an email. Which one of these are you struggling with? What have you already tried with that technology? And what didn't work, or gave a different result than you expected? – Frank van Puffelen Feb 07 '19 at 14:17
  • @FrankvanPuffelen, The fact is that I am an Android developer and Node. js do not really know.. Want to figure it out, but I need a direction to understand. Can someone do something similar and tell me? – Dmitrii Feb 07 '19 at 18:11

1 Answers1

0

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;
});
RomanK.
  • 207
  • 1
  • 8