Sending an email automatically in Firebase

If you want to generate an automatic email when a branch in your Realtime Database changes, it can be done using Firebase Cloud Functions.

First of all, install nodemailer:

shell
npm install nodemailer

nodemailer makes it easy as cake to send mails via Node.js. 🍰

Then, you will need to install Firebase CLI and init a project selecting Firebase Cloud Functions:

shell
firebase init

Firebase Cloud Functions

Then, open the file functions/index.js:

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

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

Delete the commented out code. To create a new function, you should call it exports.nameOfFunction. In this case, we will call the function to send an automatic mail as exports.sendEmail:

jsx
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const user = functions.config().gmail.user;
const pass = functions.config().gmail.pass;
const dest = functions.config().gmail.dest;
// Remember to type command before deploying → firebase functions:config:set gmail.user="EMAIL"
// Remember to type command before deploying → firebase functions:config:set gmail.pass="PASS"
// Remember to type command before deploying → firebase functions:config:set gmail.dest="DEST"

// Creating transport
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: user,
    pass: pass,
  },
});

// Sends email in case of DB change
exports.sendEmail = functions.database.ref('/posts/{pushId}/{typeOfLike}').onWrite( async (change, context) => {
    
    
    const mailOptions = {
        from: 'Erik',
        to: dest,
        subject: 'Firebase - Update ✨',
        text: `Hey! Someone gave you a ${context.params.typeOfLike.slice(0, -1)} in your ${context.params.pushId} post`
    };
    
    if(context.params.typeOfLike !== 'views') await mailTransport.sendMail(mailOptions);

    return null;
    
});

Remember to change user, pass and to with your Gmail credentials and destination mail.

Finally, deploy the new function.

shell
firebase deploy

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.