Sending Email with Firebase Functions and Sendgrid

Serverless function that allows you to send email with Sendgrid and no backend

Wed, 22 May 2019

In this post we will be using Firebase Functions to send email with Sendgrid. Sendgrid is a cloud based emailing service. The Firebase team recommends Sendgrid to developers to use with Firebase Functions. The code will make a single function that you can view in the firebase console for quick debugging.

Installation

This step can be skipped if you already have a Firebase functions project setup.

  1. initialize firebase functions via the command line

To do this you need to run the following command on your command line tool firebase init

  1. Install the needed package: firebase-functions, @sendgrid/mail and cors yarn add firebase-functions @sendgrid/mail cors

Code

Below is the full code for this example. The JSON body that is being received is simple form data and we will be sending the information to an admin to let them know that their website has collected new user data.

const functions = require("firebase-functions");
const sgMail = require("@sendgrid/mail");
const cors = require("cors")({
  origin: true
});

exports.emailMessage = functions.https.onRequest((req, res) => {
  const { name, email, phone, message } = req.body;
  return cors(req, res, () => {
    var text = `<div>
      <h4>Information</h4>
      <ul>
        <li>
          Name - ${name || ""}
        </li>
        <li>
          Email - ${email || ""}
        </li>
        <li>
          Phone - ${phone || ""}
        </li>
      </ul>
      <h4>Message</h4>
      <p>${message || ""}</p>
    </div>`;
    const msg = {
      to: "myemail@myemail.com",
      from: "no-reply@myemail.com",
      subject: `${name} sent you a new message`,
      text: text,
      html: text
    };
    sgMail.setApiKey(
      "SENDGRID API KEY"
    );
    sgMail.send(msg);
    res.status(200).send("success");
  }).catch(() => {
    res.status(500).send("error");
  });
});

This example grabs data that was sent via req.body. Once we have the data we start to construct an email. Sendgrid supports both text and html messages. In this example we craft out an html based body that uses no styling. Once we have our body, we start to create our email. The email consist of 5 fields: to, from, subject, text and html. After the email is crafted, we just need to set our Api and then attempt to send the message. If we succeed, we send a 200(okay) status code as well as a nice little success message. Errors will result in a 500(server error) status code and an error message.

Deploying

Run Firebase deploy on your command line to deploy this function.

firebase deploy --only functions

If successful, you will see it on your firebase console under the name emailMessage

Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.