Email to SMS Gateway With Twilio and AWS Lambda

July 07, 2020
Written by
Reviewed by

Email to SMS Gateway With Twilio and AWS Lambda

Even though creating an application to handle email to SMS gateway is very straightforward, most people don’t want to maintain a server to host it. In this post, we’ll show you how to create your own email to SMS gateway using a combination of Twilio SendGrid and AWS Lambda.

How does an email to SMS gateway work?

An email to SMS gateway is one of the easiest ways to ensure a message, marketing campaign, or other communication reaches a large audience. These enable a computer to send and receive SMS text messages to and from an SMS-compatible device over the global telecommunications network. 

How to create your own SMS gateway

Creating your own SMS gateway is a relatively simple process, with an easy set of instructions to follow detailed below.

Twilio SendGrid accepts the inbound email and triggers a HTTP POST to our AWS API Gateway. AWS Lambda processes the payload of the POST request and generates an outbound SMS using the Twilio Helper Library. You’ll need:

Step 1: Gather your Twilio account information

If you haven’t already set up a Twilio account and purchased a phone number, do that first. Find the details about a free trial here

You’ll also need the following information in this next step:

  • Account SID: Located on the Console home screen
  • Auth Token: Located on the Console home screen
  • Twilio Phone Number: Located on the Buy a Number page on the Console home screen

Step 2: Download the sample code

Since AWS Lambda doesn’t allow you to install npm packages through its online interface, we’ll package up the code and npm packages offline. 

In this section, we’ll download the code and npm packages. Then, we’ll add them to a zip file for uploading to AWS later. Here are the steps:

  1. Download or clone this repo to your desktop. 
  2. Add the cd into the directory and run npm install.
  3. Zip the entire directory.
Zip up a directory to deploy on Lambda

You’ll upload this to AWS Lambda in the next step. 

If you're curious, the core logic lives in the index.js file. Here’s an excerpt of the code you can find in the above repo:

exports.handler = async (event) => {
  let data = await parser.parse(event);

  console.log("input data: ", data);

  if (validateSender(data.from)) {
    // parse the to number from the left-hand side of the email address

    let regexp = /(^.\d+[^@])/g;

    let to = data.to.match(regexp)[0];

    let body = `Subject: ${data.subject}\nMessage: ${data.text}`;

    let message = await client.messages.create({
      body: body,

      from: process.env.FROM,

      to: to,
    });

    console.log("Message Output: ", message);

    const response = {
      statusCode: 200,

      body: JSON.stringify({ input: data, output: message }),
    };

    return response;
  } else {
    const response = {
      statusCode: 403,

      body: "Unauthorized Sender",
    };

    return response;
  }
};

This code performs the following steps:

  • Parses out the from, to, body, and subject from the payload sent by Twilio SendGrid.
  • Checks the from address domain against a list of allowed sending domains.
  • Extracts the phone number from the to address.
  • Creates a SMS message with help from the Twilio Helper Library.

Now you have a function prepared to forward email to SMS. Next, we’ll upload the code, set the environment variables, and set up the API Gateway.

Step 3: Set up the Lambda Function and API Gateway

With the code needed to forward emails to SMS, we can zip everything up, upload it to AWS, and use the API Gateway to provide a route.

Add a new Lambda Function

Navigate to Lambda in the AWS console
  1. Navigate to Lambda by searching “Lambda” under “Find Services” in the AWS Console.
  2. Click “Create Function.”
  3. Select “Author From Scratch,” provide a name for the function, and select “Runtime Node.js 12.x.”
  4. Click “Create Function” again.

Upload a zip file

Now you’ve created a function and can add the code we’ve prepared. At this point, you’ll need to upload the zip file with our assets.

Select “Upload a .zip file” in the Function code section.

Upload a .zip file option in AWS Lambda

Then pick the zip file we created earlier.

Add environment variables

In our code, we left some sections populated with variables. Enter those environment variables in a secure screen in Lambda.

Edit environment variables inside AWS Lambda

In the Environment variable section, create 4 variables:

  • Auth_Token: Gather from Step 1
  • Account_SID: Gather from Step 1
  • From: Gather phone number from Step 1
  • Domains: Gather a comma-separated list of domains allowed to send email to this gateway

Add a trigger and set up API Gateway

Everything you need to set up with the code is complete. At this point, we only need a way to trigger the function—that’s where API Gateway comes into play. 

From the Lambda Function Designer, click “Add trigger.

Add a trigger in Lambda Function Designer

Select “API Gateway.” Check “REST API” and add multipart/form-data to the binary media types.

Multi-part form data in API Gateway

Click “Add” after you fill out the form. Finally, copy the URL of the API endpoint.

Get the URL of the API Gateway endpoint

Now you have a new route that will trigger the Lambda Function you uploaded. Next, we’ll configure Twilio SendGrid to hit that route on an incoming email.

Step 4: Twilio SendGrid setup

With our forwarding function and route in place, we only need to trigger the setup when we receive an email. We’re going to use Twilio SendGrid’s Inbound Parse feature. 

This article assumes you have already set up a Twilio SendGrid account and configured the domain name system, or DNS, for your domain. If you haven’t done so, follow the instructions outlined here

From the Twilio SendGrid Console, navigate to settings -> Inbound Parse.

SendGrid inbound parse setup

Click “Add Host & URL.”

Add a host & url in the SendGrid console for inbound parse

Any email sent to this host will trigger a HTTP POST to the destination URL provided—for example, to 18885554444@smsgateway.example.com

Test time! 

Now try and send a test email—it should show up on your mobile device.

Email:

Test email example to trigger an SMS

Resulting SMS:

SMS triggered off a test email

Why didn’t I use Twilio Functions?

Twilio Functions would be a natural solution for this. Unfortunately, Twilio Functions, along with many other cloud function solutions, doesn’t support binary content types such as multipart/form-data. AWS, however, made some recent changes to its API Gateway that enable binary content types.

Want to add more email to SMS features?

Congratulations! You now have a serverless solution to forward incoming emails to SMS using Twilio SendGrid, Programmable SMS, and AWS Lambda. If you’d like to continue building this solution, here are some ideas:

  • Enhance the domain validation for specific senders.
  • Handle responses to these SMS messages.
  • Support predefined recipient groups.

We can’t wait to see what you build!

Sign up and start building. Not ready yet? Talk to an expert.