Skip to contentSkip to navigationSkip to topbar
On this page

Receive and Download Images on Incoming Media Messages with Ruby and Sinatra


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 Ruby.


Create MMS processing project

create-mms-processing-project page anchor

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 in Ruby is to use the Sinatra web framework(link takes you to an external page).

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-ruby helper library to facilitate generating TwiML and the rest of the webhook plumbing.

To install Sinatra and the Twilio library, open your terminal and run the following:

1
gem install sinatra
2
gem install twilio-ruby

Receive MMS message and images

receive-mms-message-and-images page anchor

Get incoming message details

get-incoming-message-details page anchor

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.

Get number of attachments

get-number-of-attachments page anchor

We may receive more than one media per message, so this parameter informs us how many we received. We also cast it to an Integer, to be used in a following loop:

num_media = params['NumMedia'].to_i

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:

1
for i in 0..(num_media - 1) do
2
media_url = params["MediaUrl#{i}"]
3
end

Determine content type of media

determine-content-type-of-media page anchor

Attachments to MMS messages can be of many different file types. JPG(link takes you to an external page) and GIF(link takes you to an external page) images as well as MP4(link takes you to an external page) and 3GP(link takes you to an external page) 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. We will also use the mime-types gem to get the file extension from its type.

1
for i in 0..(num_media - 1) do
2
media_url = params["MediaUrl#{i}"]
3
content_type = params["MediaContentType#{i}"]
4
end

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:

  1. They are publicly accessible without any need for authentication to facilitate sharing.
  2. They are permanent (unless you explicitly delete the media, see later).

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.

Save media to local file system

save-media-to-local-file-system page anchor

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. Figuring out a good extension to use is a little tricker. If you are only expecting images, you could just assume a ".jpg" extension. For a little more flexibility, you can lookup the mime type and determine a good extension to use based on that.

Here's the complete code for our view that saves each MMS attachment to the current folder.

Receive MMS images with Ruby

receive-mms-images-with-ruby page anchor
1
require 'open-uri'
2
require 'mime-types'
3
require 'sinatra'
4
require 'twilio-ruby'
5
6
post '/sms' do
7
num_media = params['NumMedia'].to_i
8
9
if num_media > 0
10
for i in 0..(num_media - 1) do
11
# Prepare the file information
12
media_url = params["MediaUrl#{i}"]
13
content_type = params["MediaContentType#{i}"]
14
file_name = media_url.split('/').last
15
file_extension = MIME::Types[content_type].first.extensions.first
16
file = "#{file_name}.#{file_extension}"
17
18
# Dowload the files
19
open(media_url) do |url|
20
File.open(file, 'wb') do |f|
21
f.write(url.read)
22
end
23
end
24
25
end
26
end
27
28
# Reply message
29
twiml = Twilio::TwiML::MessagingResponse.new do |resp|
30
body = num_media > 0 ? "Thanks for sending us #{num_media} file(s)!" : 'Send us an image!'
31
resp.message body: body
32
end
33
34
content_type 'text/xml'
35
twiml.to_s
36
end

Another idea for these image files could be uploading them to a cloud storage service like Azure Blob Storage(link takes you to an external page) or Amazon S3(link takes you to an external page). 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 database in order to retrieve them later.

Delete media from Twilio

delete-media-from-twilio page anchor

If you are downloading the attachments and no longer need them to be stored by Twilio, you can delete them by making an HTTP DELETE request to the media URL. You will need to be authenticated to do this. The code sample below demonstrates how to do this.

Delete a MediaLink to code sample: Delete a Media
1
# Download the helper library from https://www.twilio.com/docs/ruby/install
2
require 'rubygems'
3
require 'twilio-ruby'
4
5
# Find your Account SID and Auth Token at twilio.com/console
6
# and set the environment variables. See http://twil.io/secure
7
account_sid = ENV['TWILIO_ACCOUNT_SID']
8
auth_token = ENV['TWILIO_AUTH_TOKEN']
9
@client = Twilio::REST::Client.new(account_sid, auth_token)
10
11
@client
12
.api
13
.v2010
14
.messages('MM800f449d0399ed014aae2bcc0cc2f2ec')
15
.media('ME557ce644e5ab84fa21cc21112e22c485')
16
.delete
(warning)

Protect your webhooks

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.


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(link takes you to an external page) for storage of all the media files that you keep on Twilio's servers.

We'd love to hear what you build with this.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.