Firebase cloud function to use sendgrid for sending emails when a contact form gets submitted to firestore

Viewed 1615

I want my firebase backend to send an email to me when a document is created in a firestore collection based on a form submission in my vue app..

I found sendgrid to be the easiest to get the job done, the example mentioned in the package page suggests that I store the API key in an Environment variable.
Since this will run from a cloud function, I used the following command firebase functions:config:set sendGrid.key="THE API GOES HERE" as mentioned in Firebase docs here

cloud function
I initialized the firebase cloud functions locally, then I called the admin module so i can listen to onCreate() when a document is created in firestore, I used sendGrid inside the callback function of onCreate().. I tested the code and checked the functions logs in my firebase project and it gets invoked and finished successfully with a status ok, which means that everything should be working fine.

here is my index.js code inside the /functions folder in my project root

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// sendGrid
const sgMail = require('@sendgrid/mail');

// the cloud function
exports.formSubmitted = functions.firestore.document('message/{messageId}').onCreate(doc => {
  // referencing the form data
  const formData = doc.data();

  // the following should be logged in the function logs in my firebase project 
  console.log(formData);

  // retrieving the environment variable 
  sgMail.setApiKey(functions.config().sendgrid.key);

  // the message to be sent
  const msg = {
    to: 'MY-EMAIL@gmail.com',
    from: formData.email,
    subject: 'new user submitted our contact form',
    text: formData.message,
    html: '<h3> test email from sendGrid </h3>'
  }

  return sgMail.send(msg);
})

result: everything worked fine except I didn't receive the email.

If further code/explanation is needed, please leave a comment below. any help or hints is highly appreciated, thanks in advance.

0 Answers
Related