Send Serverless Emails using SendGrid and Twilio Functions

November 20, 2019
Written by
Felistas Ngumi
Contributor
Opinions expressed by Twilio contributors are their own

Serverless Emails

Software developers are moving away from the expensive, traditional, server-based architecture platforms and shifting towards the trendy serverless applications. This new way of developing applications is event-driven, cheaper in comparison to the operating costs of maintaining a server, offers a quick way of deploying functions and allows businesses to pay for only what they use.

In this tutorial, you will learn how to send emails using Twilio Functions and SendGrid.

Project Setup

To complete this tutorial you will need the following:

  1. SendGrid Account
  2. Twilio Account
  3. Twilio CLI
  4. Node Version 8 and above.

Getting Started

After creating a free account on Twilio, install the Twilio CLI which enables you to  develop and deploy functions locally. To install the tool, run the following command in your console window.

$ brew tap twilio/brew && brew install twilio

NOTE: This command is specific to Mac users. If you are on a different platform, you can find the setup instructions here.

To confirm a successful installation of the tool, type twilio on your console and a similar screen should appear.

Console window

A clean installation of the Twilio CLI doesn’t have the serverless commands. In order to obtain this, run the following command to install the serverless plugins:

$ twilio plugins:install @twilio-labs/plugin-serverless

Log in to your Twilio account in the console and create an API key by running twilio login. You will be prompted for your Twilio  Account SID and Auth Token which can be obtained from your Twilio console.

Obtaining SendGrid API Key

You’ll need a SendGrid API key in order to send your emails. Create an account with SendGrid, then navigate to the API Keys section under settings to create one. Be sure to select the Full Access option like shown below:

SendGrid API Key

Take note of the API Key created since we are going to use it later.

Project Setup

On a new terminal window, run the following commands:

$ mkdir demo && cd demo
$ twilio serverless:init demo-email
$ cd demo-email
$ npm install @sendgrid/mail --save
$ rm -rf functions/*
$ cd functions && touch mail.js

These commands have created our functions project with the name demo-email and cleared the boilerplate code under the functions folder since we will create our function from scratch. Before we get to the exciting part, add the following keys in the .env file created.

SENDGRID_API_KEY=your_sendgrid_api_key

Be sure to check the Enable ACCOUNT_SID and AUTH_TOKEN checkbox in the configuration.

Creating Our Server Function

Add the following few lines of code inside our mail.js file.

exports.handler = function(context, event, callback) {
  const sgMail = require("@sendgrid/mail");
  sgMail.setApiKey(context.SENDGRID_API_KEY);

  const message = {
    to: "felistaswaceera@gmail.com",
    from: "trial@trail.com",
    subject: "Sending Emails with Twilio SendGrid and Twilio Server Functions is Easy",
    text: "How simple can this be?"
  };
  sgMail
    .send(message)
    .then(() => {
      callback(null, "Email sent successfully");
    })
    .catch(e => {
      console.log(e);
    });
};

In the snippet above, a function is exported while passing three arguments whose main purpose are:

  • context - an object that provides access to environment variables and helper methods within the Twilio functions execution environment.
  • event - an object containing request parameters passed into your function.
  • callback - a function that is invoked at the end of execution.

Inside the function, we are leveraging the @sendgrid/mail npm package to help us send emails via SendGrid.

Ensure to change the to key inside the message object to your own email.

Deploying and Testing Our Function

In your console, run the following command:

$ cd .. && twilio serverless:deploy

After a successful deployment, you should see a screen similar to the one below:

Console window

Copy the URL under Functions and paste it in your browser. You should expect to receive an email.

Email receipt

Testing Locally

In order to test your function locally, change the code to:

exports.handler = function(context, event, callback) {
 const sgMail = require("@sendgrid/mail");
 sgMail.setApiKey(process.env.SENDGRID_API_KEY);

 const message = {
   to: "felistaswaceera@gmail.com",
   from: "trial@trail.com",
   subject: "Sending Emails with Twilio SendGrid and Twilio Server Functions is Easy",
   text: "How simple can this be?"
 };
 sgMail
   .send(message)
   .then(() => {
     callback(null, "Email sent successfully");
   })
   .catch(e => {
     console.log(e);
   });
};

Run twilio serverless:start and copy the mail functions URL as shown below and paste in your browser.

console window

And voila, you have a new email in your inbox!

Conclusion

In this tutorial, you have learned how to send a serverless email using Twilio SendGrid and Twilio Functions. I would love to hear from you. Happy hacking!