Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Receive and Download Images on Incoming Media Messages with Python and Django


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


Create MMS processing project

create-mms-processing-project page anchor

Create a Django application

create-a-django-application page anchor

When Twilio receives a message for your phone number, it can make an HTTP call to a webhook that you create.

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.messaging_response 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:


_10
pip install twilio

Add a new route in your urls.py file that handles incoming SMS requests.

Handle Incoming SMS Routes - Django

handle-incoming-sms-routes---django page anchor

_16
from django.conf import settings
_16
from django.conf.urls import url
_16
from django.conf.urls.static import static
_16
_16
from . import views
_16
_16
urlpatterns = [
_16
url(r'^$', views.index, name='index'),
_16
url(r'^config/$', views.config, name='config'),
_16
url(r'^images/$', views.get_all_media, name='images'),
_16
url(r'^images/(?P<filename>[0-9A-Za-z\.]{0,50})$', views.handle_delete_media_file, name='delete_image'),
_16
url(r'^incoming/$', views.handle_incoming_message, name='incoming'),
_16
]
_16
_16
if settings.DEBUG:
_16
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


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.

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 request body like this:

Handle Incoming SMS Views - Django

handle-incoming-sms-views---django page anchor

_56
import os
_56
import sys
_56
import logging
_56
import mimetypes
_56
import requests
_56
_56
from django.core import serializers
_56
from django.http import HttpResponse, JsonResponse
_56
from django.shortcuts import render
_56
from django.views.decorators.csrf import csrf_exempt
_56
from core.receive_mms import *
_56
_56
_56
logger = logging.getLogger(__name__)
_56
_56
_56
def index(request):
_56
return render(request, 'receive_mms/index.html')
_56
_56
_56
def config(_):
_56
return JsonResponse({'twilioPhoneNumber': os.getenv('TWILIO_NUMBER', '')})
_56
_56
_56
# /images/
_56
def get_all_media(_):
_56
return JsonResponse({'data': fetch_all_media()})
_56
_56
_56
# /images/:filename
_56
@csrf_exempt
_56
def handle_delete_media_file(_, filename=None):
_56
try:
_56
media_content, mime_type = delete_media_file(filename)
_56
return HttpResponse(media_content, content_type=mime_type)
_56
except MMSMedia.DoesNotExist as err:
_56
logger.error(err)
_56
return JsonResponse({
_56
'status': False,
_56
'message': 'Could not find any media file with name: {}'.format(filename)
_56
}, status=404)
_56
_56
_56
# /incoming/
_56
@csrf_exempt
_56
def handle_incoming_message(request):
_56
message_sid = request.POST.get('MessageSid', '')
_56
from_number = request.POST.get('From', '')
_56
num_media = int(request.POST.get('NumMedia', 0))
_56
_56
media_files = [(request.POST.get("MediaUrl{}".format(i), ''),
_56
request.POST.get("MediaContentType{}".format(i), ''))
_56
for i in range(0, num_media)]
_56
_56
response = reply_with_twiml_message(message_sid, from_number, num_media, media_files)
_56
return HttpResponse(response, content_type='application/xml')

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.

Map MIME Type To File Extension

map-mime-type-to-file-extension page anchor

_59
import os
_59
import mimetypes
_59
import requests
_59
_59
from twilio.rest import Client
_59
from twilio.twiml.messaging_response import MessagingResponse
_59
from core.models import MMSMedia
_59
_59
# Python 2 and 3: alternative 4
_59
try:
_59
from urllib.parse import urlparse
_59
except ImportError:
_59
from urlparse import urlparse
_59
_59
_59
def reply_with_twiml_message(message_sid, from_number, num_media, media_files):
_59
if not from_number or not message_sid:
_59
raise Exception('Please provide a From Number and a Message Sid')
_59
_59
for (media_url, mime_type) in media_files:
_59
file_extension = mimetypes.guess_extension(mime_type)
_59
media_sid = os.path.basename(urlparse(media_url).path)
_59
content = requests.get(media_url).text
_59
filename = '{sid}{ext}'.format(sid=media_sid, ext=file_extension)
_59
_59
mms_media = MMSMedia(
_59
filename=filename,
_59
mime_type=mime_type,
_59
media_sid=media_sid,
_59
message_sid=message_sid,
_59
media_url=media_url,
_59
content=content)
_59
mms_media.save()
_59
_59
response = MessagingResponse()
_59
message = 'Send us an image!' if not num_media else 'Thanks for the {} images.'.format(num_media)
_59
response.message(body=message, to=from_number, from_=os.getenv('TWILIO_NUMBER'))
_59
return response
_59
_59
_59
def delete_media_file(filename=None):
_59
m = MMSMedia.objects.get(filename=filename)
_59
_twilio_client().api.messages(m.message_sid) \
_59
.media(m.media_sid) \
_59
.delete()
_59
m.delete()
_59
_59
return m.content, m.mime_type
_59
_59
_59
def fetch_all_media():
_59
return map(lambda mms: mms.filename, MMSMedia.objects.all())
_59
_59
_59
def _twilio_client():
_59
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
_59
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
_59
_59
return Client(account_sid, auth_token)


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 which makes sharing easy.
  2. They are permanent (unless you explicitly delete the media).

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:


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

Handle Incoming SMS Endpoints - Django

handle-incoming-sms-endpoints---django page anchor

_59
import os
_59
import mimetypes
_59
import requests
_59
_59
from twilio.rest import Client
_59
from twilio.twiml.messaging_response import MessagingResponse
_59
from core.models import MMSMedia
_59
_59
# Python 2 and 3: alternative 4
_59
try:
_59
from urllib.parse import urlparse
_59
except ImportError:
_59
from urlparse import urlparse
_59
_59
_59
def reply_with_twiml_message(message_sid, from_number, num_media, media_files):
_59
if not from_number or not message_sid:
_59
raise Exception('Please provide a From Number and a Message Sid')
_59
_59
for (media_url, mime_type) in media_files:
_59
file_extension = mimetypes.guess_extension(mime_type)
_59
media_sid = os.path.basename(urlparse(media_url).path)
_59
content = requests.get(media_url).text
_59
filename = '{sid}{ext}'.format(sid=media_sid, ext=file_extension)
_59
_59
mms_media = MMSMedia(
_59
filename=filename,
_59
mime_type=mime_type,
_59
media_sid=media_sid,
_59
message_sid=message_sid,
_59
media_url=media_url,
_59
content=content)
_59
mms_media.save()
_59
_59
response = MessagingResponse()
_59
message = 'Send us an image!' if not num_media else 'Thanks for the {} images.'.format(num_media)
_59
response.message(body=message, to=from_number, from_=os.getenv('TWILIO_NUMBER'))
_59
return response
_59
_59
_59
def delete_media_file(filename=None):
_59
m = MMSMedia.objects.get(filename=filename)
_59
_twilio_client().api.messages(m.message_sid) \
_59
.media(m.media_sid) \
_59
.delete()
_59
m.delete()
_59
_59
return m.content, m.mime_type
_59
_59
_59
def fetch_all_media():
_59
return map(lambda mms: mms.filename, MMSMedia.objects.all())
_59
_59
_59
def _twilio_client():
_59
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
_59
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
_59
_59
return Client(account_sid, auth_token)

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 - let your DevOps creativity run free! In this case, we are saving them to the public directory in order to serve 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 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 Python Helper Library. As shown here:

Delete Media From Twilio Servers

delete-media-from-twilio-servers page anchor

_59
import os
_59
import mimetypes
_59
import requests
_59
_59
from twilio.rest import Client
_59
from twilio.twiml.messaging_response import MessagingResponse
_59
from core.models import MMSMedia
_59
_59
# Python 2 and 3: alternative 4
_59
try:
_59
from urllib.parse import urlparse
_59
except ImportError:
_59
from urlparse import urlparse
_59
_59
_59
def reply_with_twiml_message(message_sid, from_number, num_media, media_files):
_59
if not from_number or not message_sid:
_59
raise Exception('Please provide a From Number and a Message Sid')
_59
_59
for (media_url, mime_type) in media_files:
_59
file_extension = mimetypes.guess_extension(mime_type)
_59
media_sid = os.path.basename(urlparse(media_url).path)
_59
content = requests.get(media_url).text
_59
filename = '{sid}{ext}'.format(sid=media_sid, ext=file_extension)
_59
_59
mms_media = MMSMedia(
_59
filename=filename,
_59
mime_type=mime_type,
_59
media_sid=media_sid,
_59
message_sid=message_sid,
_59
media_url=media_url,
_59
content=content)
_59
mms_media.save()
_59
_59
response = MessagingResponse()
_59
message = 'Send us an image!' if not num_media else 'Thanks for the {} images.'.format(num_media)
_59
response.message(body=message, to=from_number, from_=os.getenv('TWILIO_NUMBER'))
_59
return response
_59
_59
_59
def delete_media_file(filename=None):
_59
m = MMSMedia.objects.get(filename=filename)
_59
_twilio_client().api.messages(m.message_sid) \
_59
.media(m.media_sid) \
_59
.delete()
_59
m.delete()
_59
_59
return m.content, m.mime_type
_59
_59
_59
def fetch_all_media():
_59
return map(lambda mms: mms.filename, MMSMedia.objects.all())
_59
_59
_59
def _twilio_client():
_59
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
_59
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
_59
_59
return Client(account_sid, auth_token)

(warning)

Warning

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(link takes you to an external page). 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.


Rate this page: