Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.0.0+

Download the media files from a Twilio MMS

See more Twilio Examples

Supply the Message SID of a received or sent MMS. List its media records, then request each media resource without the .json extension to download the file bytes. Twilio may return a temporary HTTPS download URL. The example uses a separate HTTP client for that URL so the Twilio API key stays with the API host.

Run in an empty output directory. Files are written as mms-media-1.bin, mms-media-2.bin, and so on. The code prints the media SID and MIME type alongside each filename. An empty media list produces a count of zero.

Twilio documentation

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  // Load an API key for the Twilio account from private application configuration.
  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.basicAuth = true;
  http.login = 'YOUR_API_KEY_SID';
  http.password = 'YOUR_API_KEY_SECRET';

  final url = CkStringBuilder();
  url.append('https://api.twilio.com/2010-04-01/Accounts/');
  url.append('YOUR_ACCOUNT_SID');
  url.append('/Messages');
  url.append('/');
  url.append('YOUR_MESSAGE_SID');
  url.append('/Media');
  final mediaBase = CkStringBuilder();
  mediaBase.appendSb(url);
  url.append('.json');
  // Handle the API redirect explicitly so a signed download uses no Twilio credentials.
  http.followRedirects = false;
  final download = CkHttp();
  download.requireSslCertVerify = true;
  final fileResp = CkHttpResponse();
  final fileUrl = CkStringBuilder();
  final filename = CkStringBuilder();
  final mediaSid = CkStringBuilder();
  var saved = 0;
  final resp = CkHttpResponse();
  final reply = CkJsonObject();

  var more = true;
  while (more) {
    success = true;
    try {
      http.httpNoBody('GET', url.getAsString(), resp);
    } on ChilkatException {
      success = false;
    }
    if (resp.statusCode == 0) {
      print('No HTTP response from Twilio.');
      return;
    }

    var parsed = true;
    try {
      reply.load(resp.bodyStr);
    } on ChilkatException {
      parsed = false;
    }
    if ((!success) || (resp.statusCode != 200)) {
      print('Twilio returned HTTP ${resp.statusCode}');
      if ((parsed) && (reply.jsonTypeOf('code') == 2)) {
        print('Twilio error: ${reply.intOf('code')}  ${reply.stringOf('message')}');
      }

      return;
    }

    if (!parsed) {
      print('Expected a JSON response from Twilio.');
      return;
    }

    if (reply.jsonTypeOf('media_list') != 4) {
      print('Expected an array of media items.');
      return;
    }

    final count = reply.sizeOfArray('media_list');
    var i = 0;
    while (i < count) {
      reply.i = i;
      mediaSid.setString(reply.stringOf('media_list[i].sid'));
      if (mediaSid.length == 0) {
        print('Media item is missing its SID.');
        return;
      }

      fileUrl.setString(mediaBase.getAsString());
      fileUrl.append('/');
      fileUrl.appendSb(mediaSid);
      success = true;
      try {
        http.httpNoBody('GET', fileUrl.getAsString(), fileResp);
      } on ChilkatException {
        success = false;
      }
      if ((fileResp.statusCode >= 300) && (fileResp.statusCode < 400)) {
        fileUrl.setString(fileResp.getHeaderField('Location'));
        if (!fileUrl.startsWith('https://', false)) {
          print('Expected an HTTPS media download URL.');
          return;
        }

        success = true;
        try {
          download.httpNoBody('GET', fileUrl.getAsString(), fileResp);
        } on ChilkatException {
          success = false;
        }
      }

      if ((!success) || (fileResp.statusCode != 200)) {
        print('Media download failed for ${mediaSid.getAsString()}. HTTP ${fileResp.statusCode}');
        return;
      }

      filename.setString('mms-media-');
      filename.appendInt(saved + 1);
      filename.append('.bin');
      success = true;
      try {
        fileResp.saveBodyBinary(filename.getAsString());
      } on ChilkatException {
        success = false;
      }
      if (!success) {
        print(fileResp.lastErrorText);
        return;
      }

      print('${filename.getAsString()}  ${mediaSid.getAsString()}  ${reply.stringOf('media_list[i].content_type')}');
      saved++;
      i++;
    }

    if (reply.isNullOf('next_page_uri')) {
      more = false;
    } else {
      url.setString(reply.stringOf('next_page_uri'));
      if (!url.startsWith('/2010-04-01/Accounts/', true)) {
        print('Expected a Twilio relative next-page URI.');
        return;
      }

      url.prepend('https://api.twilio.com');
    }
  }

  print('Media files saved: $saved');
}