Firebase Cloud function to send emails via SendGrid



  • In this post i'm showing you how to send emails via firebase cloud functions by SendGrid. SendGrid is a cloud based email service it has free tier which will help you to begin. Also we have to enable firebase billing to work this correctly, because firebase free plan only allow google services for outbound networking.

    For this tutorial i'm assuming you have installed firebase sdk and log into your firebase account.

    Setting up things

    1. Open terminal & run firebase init to initilize firebase functions
    2. We need two packages for this, add them via npm
      1. npm install @sendgrid/mail
      2. npm install cors
    3. Now open index.js and put below code.
    const functions = require('firebase-functions');
    
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    const SENDGRID_API_KEY = "PUT_YOUR_SENDGRID_API_KEY";
    
    const sgMail = require('@sendgrid/mail');
    const cors = require("cors")({
      origin: true
    });
    
    exports.sendEmail = functions.https.onRequest((req, res) => {
    	return cors(req, res, () => {
      	const msg = {
          to: req.body.email,
          from: '[email protected]',
          subject:  'SUBJECT',
          templateId: 'd-02d153b9f48f490bb73bfcc6ad92d892', //SendGrid Template ID
          // SendGrid Template Variables
          dynamic_template_data: {
            name: req.body.name,
            event_name: req.body.event,
            date: req.body.date
          }
        };
        
        sgMail.send(msg).then(res => {
          res.send({
            success: true,
            message: res
          });
        }).catch(err => {
          res.send({
            success: false,
            error: err
          });
        });
      });
    });
    
    1. Now deploy our function by running firebase deploy --only functions

    NOTE - To work this correctly, you must enable billing on your firebase account


  • Web Development

    ස්තුතියි. onCreate වගේ වෙන එකක්ද functions.https.onRequest කියන්නේ?



  • @Sahan-Pasindu-Nirmal said in Firebase Cloud function to send emails via SendGrid:

    ස්තුතියි. onCreate වගේ වෙන එකක්ද functions.https.onRequest කියන්නේ?

    ow, https.onRequest kyanne http request ekak awama execute wena method ekak


  • Linux Help

    great bro


  • Web Development

    thanks bro



  • @root @cody welcome bro