• Twilio Guides

Receive and Download Images on Incoming MMS Messages with Rails

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

Create MMS Processing Project

Create a Rails application

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 PHP is to use Rails or a similar framework. 

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 module in the helper library that can make generating the TwiML and the rest of the webhook plumbing easy peasy.

To install the library, run:

gem install twilio-ruby

Create Controller

Add a new controller called MessagingController that handles an incoming SMS request.

Loading Code Samples...
Language
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
Rails API Controller

Receive MMS Message and Images

Get Incoming Message Details

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 URLs to the Media

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:

Loading Code Samples...
Language
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
Extract Media Urls From Request Body

Determine Content Type of Media

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.

Loading Code Samples...
Language
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
Map MIME Type To File Extension

Process MMS Images

Save the Media URLs

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 make sharing easy.
  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

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.

Loading Code Samples...
Language
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
Save Media From Url

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 database in order to retrieve them later.

Delete Media from Twilio

If you are downloading the attachments and no longer need them to be stored by Twilio, you can easily 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. To make this easy, you can use the Twilio Ruby Helper Library. As shown here:

Loading Code Samples...
Language
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
Delete Media From Twilio Servers

What’s Next?

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.

Jose Oliveros
David Prothero
Samuel Mendes
Orlando Hidalgo
Kat King
Agustin Camino

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end
require 'open-uri'

class MmsResourcesController < ApplicationController
  def index
    @twilio_number = ENV.fetch('TWILIO_NUMBER')
    @files = MmsResource.all
  end

  def create
    (0..num_media - 1).each do |index|
      media_url    = params["MediaUrl#{index}"]
      content_type = params["MediaContentType#{index}"]
      message_sid  = params["MessageSid"]
      mms_resource = MmsResource.new(filename: file_name(media_url, content_type))
      IO.copy_stream(open(media_url), mms_resource.path)
      delete_media(message_sid, media_url) if mms_resource.save
    end

    message = num_media.zero? ? 'Send us an image' : 'Thanks for the images'
    response = Twilio::TwiML::MessagingResponse.new do |r|
      r.message(message: message)
    end
    render xml: response.to_xml
  end

  private

  def twilio_client
    Twilio::REST::Client.new(ENV.fetch('TWILIO_ACCOUNT_SID'), ENV.fetch('TWILIO_AUTH_TOKEN'))
  end

  def delete_media(message_sid, media_url, repetition = 0)
    Retriable.retriable(on: Twilio::REST::RestError, tries: 4, base_interval: 2) do
      twilio_client.api.accounts(ENV.fetch('TWILIO_ACCOUNT_SID'))
        .messages(message_sid)
        .media(media_id(media_url))
        .delete
    end
  end

  def num_media
    params["NumMedia"].to_i
  end

  def file_name(media_url, file_type)
    "#{media_id(media_url)}#{file_extension(file_type)}"
  end

  def file_extension(media_type)
    Rack::Mime::MIME_TYPES.invert[media_type]
  end

  def media_id(media_url)
    URI(media_url).path.split('/').last
  end
end