Using Node.js to Send MMS Messages via Twilio

, ,

Recently Twilio announced that they would begin supporting MMS in their API! We’re very excited about incorporating this into our text message marketing platform here at crosstek, so I thought I’d take a crack at sending a picture to my mobile phone with Node.js.

The code I’ll outline below works in theory, but I ran into an unexpected hiccup. Currently Twilio only supports MMS on their Canadian numbers, and apparently can’t send those MMS messages from Canadian numbers to US numbers. Hopefully this will be resolved soon and we will see some MMS love here in the US as well.

I setup a simple Node.js app skeleton with express and twilio packages. Here’s my package.json

{
"name": "twilio-node-example",
"description": "testing the new MMS function of Twilio via node.js",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.x",
"twilio": "1.2" }
}

Setup dependencies:

npm install
The app.js

var express = require('express');
var app = express();

app.get('/send',function(req,res){

	// These vars are your accountSid and authToken from twilio.com/user/account

	var accountSid = 'AC832af666a512f7edf14851909c6976f9';
	var authToken = "your-auth-token";

	var client = require('twilio')(accountSid, authToken);

	var args = req.query;

	client.messages.create({
	    body: args.message,
	    to: "+16017470702",
	    from: "+12048099999",
	    mediaUrl: args.mediaUrl	
	}, function(err, message) {
		if (err) {
			console.log(err);
			res.send(err);

		}
	    console.log(message.sid);
	    res.send(message.sid);
	});
});

app.listen(3008);

The very simple Express app above takes a GET request with “message” and “mediaUrl” parameters. These are passed to the Twilio API call which does the rest. More details over at the Twilio API Docs.

Twilio has to get the media you are sending via MMS, so the mediaURL must be Internet accessible!

Run the app:

node app.js

Test in your browser: http://localhost:3008/send?message=I%20am%20the%20danger&mediaUrl=https://s3.amazonaws.com/crosstek.net/heisenberg.gif

This is where I get an error for now.

{ status: 400, message: ‘The ‘To’ phone number: +16017470702, is not currently reachable using the ‘From’ phone number: +12048099999 via MMS.’, code: 21612, moreInfo: ‘https://www.twilio.com/docs/errors/21612′ }

If I remove the mediaURL key from the object the plain SMS does send, so I assume once MMS comes online for us non-Canadians, this code will function properly. If you are able to test this with a Canadian “To” number,  let me know! What other cool stuff are you doing or planning to try with the new MMS features in Twilio?

If you’d like to download this code, I zipped it up for you, dependencies and all. Have a great day!