This script will forward an incoming MMS image as an attachment to a email using Sendgrid. To get started you will need to setup a Sendgrid account.
Prerequisites
Create your SendGrid account
- Create an account with SendGrid. SendGrid offers 40,000 emails for 30 days, then 100 emails/day. Beyond that, you'll need to upgrade to a $14.95/mo plan that offers about 40,000 emails per month.
- Activate your SendGrid account. Open the SendGrid activation email you received in the email account you used for signup and follow the instructions.
- Once your account is setup, generate an Sengrid API key and save this as you will need this for later.
Functions
Twilio Functions are a serverless environment that allows you to host and execute small snippets of code, from inside your Twilio account. To get started, open up your Twilio console and navigate to your Functions tab. Select "Create Service" and create a new Function Service giving it a friendly name of your choice.
Now select the newly created service and look for "Settings" - This is where we will add our Environment Variables and dependencies.
Environment Variables
This Function expects three environment variables to be set. Click "Environment Variables" and add the following to your Environment.
Variable | Meaning |
---|---|
SENDGRID_API_KEY | Your SendGrid API key |
TO_EMAIL_ADDRESS | The email address to forward the message to |
FROM_EMAIL_ADDRESS | The email address that SendGrid should send the email from |
Dependencies
This Function depends on one npm module. You should add the following dependencies in your Functions configuration page.
Dependency | Version |
---|---|
got | 6.7.1 |
request-promise-native | 1.0.9 |
Code
Now we need to add some code to our Function for it to actually execute when we receive a MMS. Go back to your Functions Editor and select your new Function.
Once the editor window opens up, select "Add" followed by "Add Function"
You will then be asked to create a "path". This essentially will be our Function name.
Feel free to name your Function how you see fit.
Once you name your Function, you will see some boilerplate code populated in the editor. Select all of this code, and replace it with the entire snippet included below:
const got = require('got');
const request = require('request-promise-native');
exports.handler = function(context, event, callback) {
imagePath = event.MediaUrl0;
//read in the image here:
request({
url: imagePath,
method: 'GET',
encoding: null
})
.then(result => {
let imageBuffer = Buffer.from(result);
let imageBase64 = imageBuffer.toString('base64');
//now create the email message
const msg = {
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
}
],
attachments: [
{
content: imageBase64,
filename: "owl.png",
type: "image/png",
disposition: "attachment",
content_id: "my_image"
}
]
};
//send mail
got.post('https://api.sendgrid.com/v3/mail/send', {
headers: {
Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(msg)
})
.then(response => {
let twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
})
.catch(err => {
callback(err);
});
});
};
Then at the bottom of your Function, hit "Save" followed by "Deploy". After about 10-15 seconds your Function will be deployed and ready to go. Now we just need to link this to our Twilio phone number, so when we receive a message, this same code is executed.
Phone Numbers
This Function expects the incoming request to be a messaging Webhook. The messaging Webhook for your Twilio Phone Number must be set to the new function we created in order for this to work. You can set this by navigating to your Active Phone Numbers and selecting the Function option from the dropdown.
Under the selection "A message comes in" select "Functions", then select your service you created followed by the "Path" or name you gave your Function. The scroll to the bottom and hit "Save".
Once set, when you receive an incoming MMS message, Twilio will then execute the function selected from the dropdown and the content of the message, will be forwarded as an Email.
The parameters that will be used by the Function are the From
,Body
&MediaUrl
. To learn more about messaging parameters, please see the following documentation: Receive an inbound SMS