SendGrid Email Automation with Google Firestore Functions

Sunil Kumar
Nov 21, 2017 · 2 min read
SendGrid API Key npm install @sendgrid/mail
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const sendgridemail = require('@sendgrid/mail');
const MY_SENDGRID_API_KEY = '<add send grid api key here>'
sendgridemail.setApiKey(MY_SENDGRID_API_KEY);
exports.payEmail = functions.firestore
.document('customers/{customerId}/payments/{paymentId}') //any write to this node will trigger email
.onCreate(event => {
const customerId = event.params.customerId;const fsdb = admin.firestore()return fsdb.collection('customers').doc(customerId)
.get()
.then(doc => {
const customerdata = doc.data()const msgbody = {
to: customerdata.email,
from: 'auto-reply@xyzshopping.com',
subject: 'Payment Success - xyzshopping.com',
templateId: '<add send grid custom template id here>',
substitutionWrappers: ['{{', '}}'],
substitutions: {
name: customerdata.displayName
}
};
return payEmail.send(msgbody)
})
.then(() => console.log('payment mail sent success') )
.catch(err => console.log(err) )
});
Hello {{name}} //{name} is defined in "substitutions"Thank you for making payment!

Google Cloud Platform - Community

A collection of technical articles published or curated by Google Cloud Platform Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.

Sunil Kumar

Written by

Angular, Ionic, Capacitor Developer, WordPress WooCommerce, Google Firestore and Cloud Function Expert

Google Cloud Platform - Community

A collection of technical articles published or curated by Google Cloud Platform Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.