Tuesday, January 30, 2018

Admin email notifications with firebase database write queries (JavaScript)

Prerequisites:
  •  NodeJS with NPM installed.  
  •  Google Firebase Account
    With your favorite web app framework you can configure your web app to auto generate emails based on site user feedback.

I've used ReactJS in this case for a generic contact us model form submission.  A quick tutorial on getting started with React JS and setting up this model can be found at:

https://www.codementor.io/yurio/all-you-need-is-react-firebase-4v7g9p4kf



   In this project I adapted recipes given for firebase user authenticated additions... from sites:

https://www.menubar.io/firebase-functions-sending-emails/

and

https://github.com/firebase/functions-samples/tree/master/quickstarts/email-users

Follow the quickstart tutorial in the functions-samples link.  Namely, in setting up your gmail account to send emails via node mailer.
Once say you have your react project or whatever project using firebase set up.  You'd need to go to that particular folder and initialize firebase functions...to do this actually will require potentially a couple of proceeding console commands at the root of your project directory:

npm install firebase-functions@latest firebase-admin@latest --save
npm install -g firebase-tools
then

firebase init functions

Go into the functions directory (via command prompt or console/terminal) and type:

npm install nodemailer --save

node package manager will initialize the project with the functions folder and install (provided your acceptance) the necessary node packages.  Note:  highly recommend that you double check your git ignore file and configure the ignore for the functions folder if you are using git.

An adapted code (from the above links), for instance, in sending email notifications looks like this:

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

const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For Gmail, enable these:
// 1. https://www.google.com/settings/security/lesssecureapps
// 2. https://accounts.google.com/DisplayUnlockCaptcha
// 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 = `****@gmail.com`;
const gmailPassword = `*****`;
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword
  }
});

// // 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!");
// });
const APP_NAME = 'Cloud Storage for Firebase quickstart';
exports.sendFEmail = functions.database.ref('messages/{uid}').onWrite(event => {

    // only trigger for new users [event.data.previous.exists()]
    // do not trigger on delete [!event.data.exists()]
    if (!event.data.exists() || event.data.previous.exists()) {
      return
    }
  
    var user = event.data.val()
    console.log(user);
    var {email} = user

      const mailOptions = {
        from: `${APP_NAME} `,
        to: `****@gmail.com`
      };
    
      // The user subscribed to the newsletter.
      mailOptions.subject = `**** Contact Notice!`;
      mailOptions.text = `${user.name} sent a message!. Here is the message:  ${user.message}.  This is the sender's email address:  ${user.email}`;
      return mailTransport.sendMail(mailOptions).then(() => {
        console.log('message sent!');
      });
    })

You'll put this code say in an index.js file in the functions directory...just replace the existing default code set.

Now you can easily deploy this up to firebase...
In your project's root directory in console just type:

firebase deploy --only functions

This pushes the function up as firebase function...what does this code do?

Reading the line  "functions.database.ref('messages/{uid}').onWrite(event..."

This is an event handler set on the database called when ever a write event occurs on the database 'messages' database key.  When a post request is created on the firebase database writing a new database entry, the event handler function is called.

The event handler in this case, if you are doing further reading, refers the database entry set as 'user'.
The object 'mailOptions' is passed in turn to the mailTransport inside the method sendMail...noting for nodemailer this is parameter nature of sending mail.

Suggested reading for further firebase api documentation as related to real time database event handling:
https://firebase.google.com/docs/functions/database-events


1 comment:

Oblivion

 Between the fascination of an upcoming pandemic ridden college football season, Taylor Swift, and Kim Kardashian, wildfires, crazier weathe...