Forward incoming SMS messages to email with Node.js, SendGrid and Twilio Functions
Tags: node, twilio, email, sms
Published: 2017-07-27 10:52:29

---
title: Forward incoming SMS messages to email with Node.js, SendGrid and Twilio Functions
published: true
description: Using Twilio and SendGrid turn SMS messages into emails in just a few lines of JavaScript.
tags: node, twilio, email, sms
canonical_url: https://www.twilio.com/blog/2017/07/forward-incoming-sms-messages-to-email-with-node-js-sendgrid-and-twilio-functions.html
cover_image: https://thepracticaldev.s3.amazonaws.com/i/dcmi86d6f1skqwxr9uyr.gif
---

If you want to read incoming SMS messages sent to your Twilio number in your email then do I have a neat solution for you today. We're going to use <a href="https://www.twilio.com/functions">Twilio Functions</a> and <a href="https://sendgrid.com/">SendGrid</a> to forward SMS messages directly to your email address.

## Things you'll need

* <a href="http://twilio.com/try-twilio">A Twilio account</a> and a phone number that can receive SMS messages
* <a href="http://sendgrid.com/">A SendGrid account</a>

## Let's get building

The entire operation of forwarding SMS messages to your email address will only take one function, so we're going to build it using a <a href="https://www.twilio.com/functions">Twilio Function</a>. If you've not heard of Twilio Functions, they are a serverless environment that you can use to run Node.js code. This means we don't need a development environment or somewhere to deploy to, we just write our code in Twilio and use it.

We do need to configure some variables though.

## First up, config

In order to use the SendGrid API to send emails we need a SendGrid API key. Head to the <a href="https://app.sendgrid.com/settings/api_keys">API Keys area in the SendGrid dashboard</a> and create yourself one.

<img alt="Hit the 'Create API key' link on the API Keys dashboard page in the SendGrid admin" src="https://twilioinc.wpengine.com/wp-content/uploads/2017/07/8gjvwk4h-J5zl3Wt1CLme-6VhpYrEtbbbxlRm5mUsAgCrSrikZbOR5un7vh5oAkrIP_NiqauaYR-1EedgRXOtmMsA4NtCf1yn-XyNKNlWhp0JuV8C6paezoSdtGu8yItLbeYIeU.png" class="aligncenter">

Open up your Twilio console and head to the <a href="https://www.twilio.com/console/runtime/functions/configure">Functions configure section</a>. Add a new environment variable called `SENDGRID_API_KEY` and paste in your new API key.

We need to make two more environment variables too, one for the email you will use to receive your SMS messages and one to send them from. If you have a <a href="https://app.sendgrid.com/settings/whitelabel/domains">domain setup within SendGrid</a> then I recommend you use that, but you can use any email address you want as the sender, even the one you are sending to. 

Enter these email addresses in the environment variables section as `TO_EMAIL_ADDRESS` and `FROM_EMAIL_ADDRESS`.

<img alt="You should have three new keys and values in the environment variables section" src="https://twilioinc.wpengine.com/wp-content/uploads/2017/07/nnprxGs1d_vwXckZNHpVaqazXH9Vti6m5eYtoz-bEhqitHJiJYHwZdT7iSih4cl775rN407zBfCJ9vwy0_3LDtLKjKNL3AaZDlpKQDDoMTRlqxbNJZ37D7-ZT1JG4940C7QnCI.png" class="aligncenter">

We're done with the config, it's time to write some code.

### Let's go write a Function

Head to the <a href="https://www.twilio.com/console/runtime/functions/manage/">Functions management page</a> and create yourself a new function. Since we're dealing with incoming SMS messages, pick the "Hello SMS" template.

Normally with Node.js this would be the time to start a search for the <a href="https://www.npmjs.com/package/sendgrid">SendGrid npm package</a>, but Functions don't currently allow you to install other packages. Thankfully there is one package available to us that will help us make HTTP requests easily: <a href="https://www.npmjs.com/package/got">got</a>.

At the top of your code require the `got` module, then delete everything within the function. You should have:

```javascript
const got = require('got');

exports.handler = function(context, event, callback) {

};
```

We need to build up an API request that SendGrid will understand. There's an <a href="https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html">example of the JSON we need to send on the documentation page for the v3 API</a> that we're going to use. Let's create that as a JavaScript object with our own values, within the function:

```javascript
exports.handler = function(context, event, callback) {
  const requestBody = {
    personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
    from: { email: context.FROM_EMAIL_ADDRESS },
    subject: `New SMS message from: ${event.From}`,
    content: [
      {
        type: 'text/plain',
        value: event.Body
      }
    ]
  };
```

Here we are using `event.From` to get the number that sent us the SMS message and `event.Body` to get the text of the incoming message. The `event` object contains all the parameters that are passed to the function as part of the request.

Now we need to send this object to the API to send the email. Use `got.post` to make a POST request to the API URL, `https://api.sendgrid.com/v3/mail/send`, and pass an object of options that describes the request headers and body.

If the request succeeds we will return an empty TwiML response and if it fails we'll log that by calling the Function callback with the error.

```javascript
  got.post('https://api.sendgrid.com/v3/mail/send', {
    headers: {
      Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(requestBody)
  })
    .then(response =&gt; {
      let twiml = new Twilio.twiml.MessagingResponse();
      callback(null, twiml);
    })
    .catch(err =&gt; {
      callback(err);
    });
};
```

And that's all the code!

Give your Function a name that makes it easy to remember and a path and save it.

<img alt="Add a name to your function in the 'Function name' field, a path in the 'Path' field and save it with the button at the bottom of the page." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/07/9vyk8JRd-RBLDQ4xXORDrDWQN2iTKNJYgQE-9c1C-k8uteskEI0BNR0LLgMSp7DZkVr3pE7QA6mQQi37TrnApSWcszKEKNZ0THyhPJpzJrEHpLBDL0qVPneDlP52WXuYzCGVArc.png" class="aligncenter">

### Hooking up your Twilio number

All that is left to do is hook up your Twilio number to your Function. Go to the <a href="https://www.twilio.com/console/phone-numbers/incoming">numbers section of the Twilio console</a> and edit the number you want to use. In the messaging section, where it says "A message comes in" choose Function, then select your Function from the drop down.

<img alt="On the phone number edit screen, configure the messaging section with 'Webhooks, TwiML Bins or Functions', choose 'Function' for when a message comes in and then pick your function from the resulting drop down." src="https://twilioinc.wpengine.com/wp-content/uploads/2017/07/t5QyneIwNseDhtcZ2if42a0nS4jEak8rUF2EczSob807__O5OycpBayF-YOiJWjcAyxupa_vqjR81evq71WXqnXhrM0b6T7OpDvP03L3Wb2MBnZr6KsUhzsXbH9wv3-F0dKM2H4.png" class="aligncenter">

Hit the save button and you're done!

### Testing

Time to test your new Function. Send a text message to your Twilio number and open up your email. 

<img alt="An image of the message I sent myself in my email client. It worked!" src="https://twilioinc.wpengine.com/wp-content/uploads/2017/07/l0gPA9piDWcgVbe6HdoWQVOOfxxkWjEZ2DgBJehT_IzeRVXiH71qM-slhGq92FzhXsz3cDIh0jvAreoDP2qKivYgsRmWPcFMYVoqqzgCavr5fvekwVXEoqrq7XmR88lGozmdCsM.png" class="aligncenter">

<em>Note: if you do not have a domain set up with SendGrid check your spam folder for the email. If you're using gmail, like I am, you can add an exception for the email address to never send it to spam and always receive your incoming messages.</em>

## Twilio Functions make the plumbing easy

With a Twilio Function and 31 lines of Node.js we set up forwarding SMS messages to email using the SendGrid API and we didn't even need our own server. Twilio Functions are really useful for bits of plumbing like this for Twilio numbers.

I got excited about this and started a <a href="https://github.com/philnash/useful-twilio-functions">repo of useful Twilio Functions</a>, including <a href="https://github.com/philnash/useful-twilio-functions/tree/master/forward-message-as-email">the one that we built in this post</a>, that are tested and ready for you to use. There's only a few available so far but since it's an open repo you can either <a href="https://github.com/philnash/useful-twilio-functions/issues">request new Functions in the issues</a> or submit your own via pull request.

I'll be adding to the repo and I'd love to see your contributions too!

Got any questions about using Twilio Functions or built anything cool with them? Drop me a note in the comments below or hit me up on <a href="https://twitter.com/philnash">Twitter</a>.

___

_[Forward incoming SMS messages to email with Node.js, SendGrid and Twilio Functions](https://www.twilio.com/blog/2017/07/forward-incoming-sms-messages-to-email-with-node-js-sendgrid-and-twilio-functions.html) was originally published on the [Twilio blog](https://www.twilio.com/blog) on July 18, 2017._