Twilio SMS to email forwarding using Sendgrid for MFA

Original Instructions

Set up Shared Mailbox

Create a shared mailbox i.e. sms@domain.com and add delegates to this mailbox

Set up SendGrid API (or equivalent)

https://app.sendgrid.com/settings/api_keys

Create a new Function

If you are using sub-accounts be sure you are in the right one https://www.twilio.com/console/functions/manage

Function Name: Forward SMS to SendGrid email

Path: /sms-to-email

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const got = require('got');

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
      }
    ]
  };
    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 => {
      let twiml = new Twilio.twiml.MessagingResponse();
      callback(null, twiml);
    })
    .catch(err => {
      callback(err);
    });
};

Configure the Function

https://www.twilio.com/console/functions/configure

KeyValue
FROM_EMAIL_ADDRESSsms@domain.com
TO_EMAIL_ADDRESSsms@domain.com
SENDGRID_API_KEY**********

Add ‘got’ version 8.3.1 in Dependencies

alt text

Set up number

https://www.twilio.com/console/phone-numbers Messaging → A Message comes in → Function → Forward SMS to SendGrid Email

Testing / Troubleshooting

Send a text to your number and ensure it is working. You can trace the message using the Twilio and Sendgrid logs:

Twilio Logs → Message Log

Sendgrid Logs