You know how to receive and reply to incoming SMS messages. What if you receive an MMS message containing an image you'd like to download? Let's learn how we can grab that image and any other incoming MMS media using Node.js.
When Twilio receives a message for your phone number, it can make an HTTP call to a webhook that you create. The easiest way to handle HTTP requests with Node is to use Express.
Twilio expects, at the very least, for your webhook to return a 200 OK
response if everything is peachy. Often, however, you will return some TwiML in your response as well. TwiML is just a set of XML commands telling Twilio how you'd like it to respond to your message. Rather than manually generating the XML, we'll use the Twilio.twiml.MessagingResponse
module in the helper library to facilitate generating TwiML and the rest of the webhook plumbing.
To install the library, run:
npm install twilio
Add a new router called MessagingRouter that handles an incoming SMS request.
1const express = require('express');2const Twilio = require('twilio');3const extName = require('ext-name');4const urlUtil = require('url');5const path = require('path');6const fs = require('fs');7const fetch = require('node-fetch');8const config = require('../config');910const PUBLIC_DIR = './public/mms_images';11const { twilioPhoneNumber, twilioAccountSid, twilioAuthToken } = config;12const { MessagingResponse } = Twilio.twiml;13const { NODE_ENV } = process.env;1415function MessagingRouter() {16let twilioClient;17let images = [];1819if (!fs.existsSync(PUBLIC_DIR)) {20fs.mkdirSync(path.resolve(PUBLIC_DIR));21}2223function getTwilioClient() {24return twilioClient || new Twilio(twilioAccountSid, twilioAuthToken);25}2627function deleteMediaItem(mediaItem) {28const client = getTwilioClient();2930return client31.api.accounts(twilioAccountSid)32.messages(mediaItem.MessageSid)33.media(mediaItem.mediaSid).remove();34}3536async function SaveMedia(mediaItem) {37const { mediaUrl, filename } = mediaItem;38if (NODE_ENV !== 'test') {39const fullPath = path.resolve(`${PUBLIC_DIR}/${filename}`);4041if (!fs.existsSync(fullPath)) {42const response = await fetch(mediaUrl);43const fileStream = fs.createWriteStream(fullPath);4445response.body.pipe(fileStream);4647deleteMediaItem(mediaItem);48}4950images.push(filename);51}52}535455async function handleIncomingSMS(req, res) {56const { body } = req;57const { NumMedia, From: SenderNumber, MessageSid } = body;58let saveOperations = [];59const mediaItems = [];6061for (var i = 0; i < NumMedia; i++) { // eslint-disable-line62const mediaUrl = body[`MediaUrl${i}`];63const contentType = body[`MediaContentType${i}`];64const extension = extName.mime(contentType)[0].ext;65const mediaSid = path.basename(urlUtil.parse(mediaUrl).pathname);66const filename = `${mediaSid}.${extension}`;6768mediaItems.push({ mediaSid, MessageSid, mediaUrl, filename });69saveOperations = mediaItems.map(mediaItem => SaveMedia(mediaItem));70}7172await Promise.all(saveOperations);7374const messageBody = NumMedia === 0 ?75'Send us an image!' :76`Thanks for sending us ${NumMedia} file(s)`;7778const response = new MessagingResponse();79response.message({80from: twilioPhoneNumber,81to: SenderNumber,82}, messageBody);8384return res.send(response.toString()).status(200);85}868788function getRecentImages() {89return images;90}9192function clearRecentImages() {93images = [];94}9596function fetchRecentImages(req, res) {97res.status(200).send(getRecentImages());98clearRecentImages();99}100101/**102* Initialize router and define routes.103*/104const router = express.Router();105router.post('/incoming', handleIncomingSMS);106router.get('/config', (req, res) => {107res.status(200).send({ twilioPhoneNumber });108});109router.get('/images', fetchRecentImages);110111return router;112}113114module.exports = {115MessagingRouter,116};
When Twilio calls your webhook, it sends a number of parameters about the message you just received. Most of these, such as the To
phone number, the From
phone number, and the Body
of the message are available as properties of the request body.
Since an MMS message can have multiple attachments, Twilio will send us form variables named MediaUrlX
, where X is a zero-based index. So, for example, the URL for the first media attachment will be in the MediaUrl0
parameter, the second in MediaUrl1
, and so on.
In order to handle a dynamic number of attachments, we pull the URLs out of the body request like this:
1const express = require('express');2const Twilio = require('twilio');3const extName = require('ext-name');4const urlUtil = require('url');5const path = require('path');6const fs = require('fs');7const fetch = require('node-fetch');8const config = require('../config');910const PUBLIC_DIR = './public/mms_images';11const { twilioPhoneNumber, twilioAccountSid, twilioAuthToken } = config;12const { MessagingResponse } = Twilio.twiml;13const { NODE_ENV } = process.env;1415function MessagingRouter() {16let twilioClient;17let images = [];1819if (!fs.existsSync(PUBLIC_DIR)) {20fs.mkdirSync(path.resolve(PUBLIC_DIR));21}2223function getTwilioClient() {24return twilioClient || new Twilio(twilioAccountSid, twilioAuthToken);25}2627function deleteMediaItem(mediaItem) {28const client = getTwilioClient();2930return client31.api.accounts(twilioAccountSid)32.messages(mediaItem.MessageSid)33.media(mediaItem.mediaSid).remove();34}3536async function SaveMedia(mediaItem) {37const { mediaUrl, filename } = mediaItem;38if (NODE_ENV !== 'test') {39const fullPath = path.resolve(`${PUBLIC_DIR}/${filename}`);4041if (!fs.existsSync(fullPath)) {42const response = await fetch(mediaUrl);43const fileStream = fs.createWriteStream(fullPath);4445response.body.pipe(fileStream);4647deleteMediaItem(mediaItem);48}4950images.push(filename);51}52}535455async function handleIncomingSMS(req, res) {56const { body } = req;57const { NumMedia, From: SenderNumber, MessageSid } = body;58let saveOperations = [];59const mediaItems = [];6061for (var i = 0; i < NumMedia; i++) { // eslint-disable-line62const mediaUrl = body[`MediaUrl${i}`];63const contentType = body[`MediaContentType${i}`];64const extension = extName.mime(contentType)[0].ext;65const mediaSid = path.basename(urlUtil.parse(mediaUrl).pathname);66const filename = `${mediaSid}.${extension}`;6768mediaItems.push({ mediaSid, MessageSid, mediaUrl, filename });69saveOperations = mediaItems.map(mediaItem => SaveMedia(mediaItem));70}7172await Promise.all(saveOperations);7374const messageBody = NumMedia === 0 ?75'Send us an image!' :76`Thanks for sending us ${NumMedia} file(s)`;7778const response = new MessagingResponse();79response.message({80from: twilioPhoneNumber,81to: SenderNumber,82}, messageBody);8384return res.send(response.toString()).status(200);85}868788function getRecentImages() {89return images;90}9192function clearRecentImages() {93images = [];94}9596function fetchRecentImages(req, res) {97res.status(200).send(getRecentImages());98clearRecentImages();99}100101/**102* Initialize router and define routes.103*/104const router = express.Router();105router.post('/incoming', handleIncomingSMS);106router.get('/config', (req, res) => {107res.status(200).send({ twilioPhoneNumber });108});109router.get('/images', fetchRecentImages);110111return router;112}113114module.exports = {115MessagingRouter,116};
Attachments to MMS messages can be of many different file types. JPG and GIF images, as well as MP4 and 3GP files, are all common. Twilio handles the determination of the file type for you and you can get the standard mime type from the MediaContentTypeX
parameter. If you are expecting photos, then you will likely see a lot of attachments with the mime type image/jpeg
.
1const express = require('express');2const Twilio = require('twilio');3const extName = require('ext-name');4const urlUtil = require('url');5const path = require('path');6const fs = require('fs');7const fetch = require('node-fetch');8const config = require('../config');910const PUBLIC_DIR = './public/mms_images';11const { twilioPhoneNumber, twilioAccountSid, twilioAuthToken } = config;12const { MessagingResponse } = Twilio.twiml;13const { NODE_ENV } = process.env;1415function MessagingRouter() {16let twilioClient;17let images = [];1819if (!fs.existsSync(PUBLIC_DIR)) {20fs.mkdirSync(path.resolve(PUBLIC_DIR));21}2223function getTwilioClient() {24return twilioClient || new Twilio(twilioAccountSid, twilioAuthToken);25}2627function deleteMediaItem(mediaItem) {28const client = getTwilioClient();2930return client31.api.accounts(twilioAccountSid)32.messages(mediaItem.MessageSid)33.media(mediaItem.mediaSid).remove();34}3536async function SaveMedia(mediaItem) {37const { mediaUrl, filename } = mediaItem;38if (NODE_ENV !== 'test') {39const fullPath = path.resolve(`${PUBLIC_DIR}/${filename}`);4041if (!fs.existsSync(fullPath)) {42const response = await fetch(mediaUrl);43const fileStream = fs.createWriteStream(fullPath);4445response.body.pipe(fileStream);4647deleteMediaItem(mediaItem);48}4950images.push(filename);51}52}535455async function handleIncomingSMS(req, res) {56const { body } = req;57const { NumMedia, From: SenderNumber, MessageSid } = body;58let saveOperations = [];59const mediaItems = [];6061for (var i = 0; i < NumMedia; i++) { // eslint-disable-line62const mediaUrl = body[`MediaUrl${i}`];63const contentType = body[`MediaContentType${i}`];64const extension = extName.mime(contentType)[0].ext;65const mediaSid = path.basename(urlUtil.parse(mediaUrl).pathname);66const filename = `${mediaSid}.${extension}`;6768mediaItems.push({ mediaSid, MessageSid, mediaUrl, filename });69saveOperations = mediaItems.map(mediaItem => SaveMedia(mediaItem));70}7172await Promise.all(saveOperations);7374const messageBody = NumMedia === 0 ?75'Send us an image!' :76`Thanks for sending us ${NumMedia} file(s)`;7778const response = new MessagingResponse();79response.message({80from: twilioPhoneNumber,81to: SenderNumber,82}, messageBody);8384return res.send(response.toString()).status(200);85}868788function getRecentImages() {89return images;90}9192function clearRecentImages() {93images = [];94}9596function fetchRecentImages(req, res) {97res.status(200).send(getRecentImages());98clearRecentImages();99}100101/**102* Initialize router and define routes.103*/104const router = express.Router();105router.post('/incoming', handleIncomingSMS);106router.get('/config', (req, res) => {107res.status(200).send({ twilioPhoneNumber });108});109router.get('/images', fetchRecentImages);110111return router;112}113114module.exports = {115MessagingRouter,116};
Depending on your use case, storing the URLs of the images (or videos or whatever) may be all you need. There are two key features to these URLs that make them very pliable for your use in your apps:
For example, if you are building a browser-based app that needs to display the images, all you need to do is drop an <img src="twilio url to your image">
tag into the page. If this works for you, then perhaps all you need is to store the URL in a database character field.
If you want to save the media attachments to a file, then you will need to make an HTTP request to the media URL and write the response stream to a file. If you need a unique filename, you can use the last part of the media URL. For example, suppose your media URL is the following:
https://api.twilio.com/2010-04-01/Accounts/ACxxxx/Messages/MMxxxx/Media/ME27be8a708784242c0daee207ff73db67
You can use that last part of the URL as a unique filename and look up the corresponding file extension for the mime type.
1const express = require('express');2const Twilio = require('twilio');3const extName = require('ext-name');4const urlUtil = require('url');5const path = require('path');6const fs = require('fs');7const fetch = require('node-fetch');8const config = require('../config');910const PUBLIC_DIR = './public/mms_images';11const { twilioPhoneNumber, twilioAccountSid, twilioAuthToken } = config;12const { MessagingResponse } = Twilio.twiml;13const { NODE_ENV } = process.env;1415function MessagingRouter() {16let twilioClient;17let images = [];1819if (!fs.existsSync(PUBLIC_DIR)) {20fs.mkdirSync(path.resolve(PUBLIC_DIR));21}2223function getTwilioClient() {24return twilioClient || new Twilio(twilioAccountSid, twilioAuthToken);25}2627function deleteMediaItem(mediaItem) {28const client = getTwilioClient();2930return client31.api.accounts(twilioAccountSid)32.messages(mediaItem.MessageSid)33.media(mediaItem.mediaSid).remove();34}3536async function SaveMedia(mediaItem) {37const { mediaUrl, filename } = mediaItem;38if (NODE_ENV !== 'test') {39const fullPath = path.resolve(`${PUBLIC_DIR}/${filename}`);4041if (!fs.existsSync(fullPath)) {42const response = await fetch(mediaUrl);43const fileStream = fs.createWriteStream(fullPath);4445response.body.pipe(fileStream);4647deleteMediaItem(mediaItem);48}4950images.push(filename);51}52}535455async function handleIncomingSMS(req, res) {56const { body } = req;57const { NumMedia, From: SenderNumber, MessageSid } = body;58let saveOperations = [];59const mediaItems = [];6061for (var i = 0; i < NumMedia; i++) { // eslint-disable-line62const mediaUrl = body[`MediaUrl${i}`];63const contentType = body[`MediaContentType${i}`];64const extension = extName.mime(contentType)[0].ext;65const mediaSid = path.basename(urlUtil.parse(mediaUrl).pathname);66const filename = `${mediaSid}.${extension}`;6768mediaItems.push({ mediaSid, MessageSid, mediaUrl, filename });69saveOperations = mediaItems.map(mediaItem => SaveMedia(mediaItem));70}7172await Promise.all(saveOperations);7374const messageBody = NumMedia === 0 ?75'Send us an image!' :76`Thanks for sending us ${NumMedia} file(s)`;7778const response = new MessagingResponse();79response.message({80from: twilioPhoneNumber,81to: SenderNumber,82}, messageBody);8384return res.send(response.toString()).status(200);85}868788function getRecentImages() {89return images;90}9192function clearRecentImages() {93images = [];94}9596function fetchRecentImages(req, res) {97res.status(200).send(getRecentImages());98clearRecentImages();99}100101/**102* Initialize router and define routes.103*/104const router = express.Router();105router.post('/incoming', handleIncomingSMS);106router.get('/config', (req, res) => {107res.status(200).send({ twilioPhoneNumber });108});109router.get('/images', fetchRecentImages);110111return router;112}113114module.exports = {115MessagingRouter,116};
Another idea for these image files could be uploading them to a cloud storage service like Azure Blob Storage or Amazon S3. You could also save them to a database, if necessary. They're just regular files at this point. Go crazy. In this case, we are saving them to the public directory in order to serve them later.
If you are downloading the attachments and no longer need them to be stored by Twilio, you can delete them. You can send an HTTP DELETE
request to the media URL and it will be deleted, but you will need to be authenticated to do this. The Twilio Node Helper Library can help with this, as shown here:
1const express = require('express');2const Twilio = require('twilio');3const extName = require('ext-name');4const urlUtil = require('url');5const path = require('path');6const fs = require('fs');7const fetch = require('node-fetch');8const config = require('../config');910const PUBLIC_DIR = './public/mms_images';11const { twilioPhoneNumber, twilioAccountSid, twilioAuthToken } = config;12const { MessagingResponse } = Twilio.twiml;13const { NODE_ENV } = process.env;1415function MessagingRouter() {16let twilioClient;17let images = [];1819if (!fs.existsSync(PUBLIC_DIR)) {20fs.mkdirSync(path.resolve(PUBLIC_DIR));21}2223function getTwilioClient() {24return twilioClient || new Twilio(twilioAccountSid, twilioAuthToken);25}2627function deleteMediaItem(mediaItem) {28const client = getTwilioClient();2930return client31.api.accounts(twilioAccountSid)32.messages(mediaItem.MessageSid)33.media(mediaItem.mediaSid).remove();34}3536async function SaveMedia(mediaItem) {37const { mediaUrl, filename } = mediaItem;38if (NODE_ENV !== 'test') {39const fullPath = path.resolve(`${PUBLIC_DIR}/${filename}`);4041if (!fs.existsSync(fullPath)) {42const response = await fetch(mediaUrl);43const fileStream = fs.createWriteStream(fullPath);4445response.body.pipe(fileStream);4647deleteMediaItem(mediaItem);48}4950images.push(filename);51}52}535455async function handleIncomingSMS(req, res) {56const { body } = req;57const { NumMedia, From: SenderNumber, MessageSid } = body;58let saveOperations = [];59const mediaItems = [];6061for (var i = 0; i < NumMedia; i++) { // eslint-disable-line62const mediaUrl = body[`MediaUrl${i}`];63const contentType = body[`MediaContentType${i}`];64const extension = extName.mime(contentType)[0].ext;65const mediaSid = path.basename(urlUtil.parse(mediaUrl).pathname);66const filename = `${mediaSid}.${extension}`;6768mediaItems.push({ mediaSid, MessageSid, mediaUrl, filename });69saveOperations = mediaItems.map(mediaItem => SaveMedia(mediaItem));70}7172await Promise.all(saveOperations);7374const messageBody = NumMedia === 0 ?75'Send us an image!' :76`Thanks for sending us ${NumMedia} file(s)`;7778const response = new MessagingResponse();79response.message({80from: twilioPhoneNumber,81to: SenderNumber,82}, messageBody);8384return res.send(response.toString()).status(200);85}868788function getRecentImages() {89return images;90}9192function clearRecentImages() {93images = [];94}9596function fetchRecentImages(req, res) {97res.status(200).send(getRecentImages());98clearRecentImages();99}100101/**102* Initialize router and define routes.103*/104const router = express.Router();105router.post('/incoming', handleIncomingSMS);106router.get('/config', (req, res) => {107res.status(200).send({ twilioPhoneNumber });108});109router.get('/images', fetchRecentImages);110111return router;112}113114module.exports = {115MessagingRouter,116};
Twilio supports HTTP Basic and Digest Authentication. Authentication allows you to password protect your TwiML URLs on your web server so that only you and Twilio can access them. Learn more about HTTP authentication and validating incoming requests here.
All the code, in a complete working project, is available on GitHub. If you need to dig a bit deeper, you can head over to our API Reference and learn more about the Twilio webhook request and the REST API Media resource. Also, you will want to be aware of the pricing for storage of all the media files that you keep on Twilio's servers.
We'd love to hear what you build with this.