Sample code for 30+ languages & platforms
Lazarus Pascal 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 Lazarus Pascal Downloads

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Http,
  Chilkat.StringBuilder,
  Chilkat.HttpResponse,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  http: THttp;
  url: TStringBuilder;
  mediaBase: TStringBuilder;
  download: THttp;
  fileResp: THttpResponse;
  fileUrl: TStringBuilder;
  filename: TStringBuilder;
  mediaSid: TStringBuilder;
  saved: Integer;
  resp: THttpResponse;
  reply: TJsonObject;
  more: Boolean;
  parsed: Boolean;
  count: Integer;
  i: Integer;

begin
  success := False;

  //  Assumes Chilkat is unlocked. See Global Unlock Sample.
  //  Load an API key for the Twilio account from private application configuration.
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  http.BasicAuth := True;
  http.Login := 'YOUR_API_KEY_SID';
  http.Password := 'YOUR_API_KEY_SECRET';

  url := TStringBuilder.Create;
  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');
  mediaBase := TStringBuilder.Create;
  mediaBase.AppendSb(url);
  url.Append('.json');
  //  Handle the API redirect explicitly so a signed download uses no Twilio credentials.
  http.FollowRedirects := False;
  download := THttp.Create;
  download.RequireSslCertVerify := True;
  fileResp := THttpResponse.Create;
  fileUrl := TStringBuilder.Create;
  filename := TStringBuilder.Create;
  mediaSid := TStringBuilder.Create;
  saved := 0;
  resp := THttpResponse.Create;
  reply := TJsonObject.Create;

  more := True;
  while (more = True) do
    begin
      success := http.HttpNoBody('GET',url.GetAsString(),resp);
      if (resp.StatusCode = 0) then
        begin
          WriteLn('No HTTP response from Twilio.');
          Exit;
        end;
      parsed := reply.Load(resp.BodyStr);
      if ((success <> True) or (resp.StatusCode <> 200)) then
        begin
          WriteLn('Twilio returned HTTP ' + resp.StatusCode);
          if ((parsed = True) and (reply.JsonTypeOf('code') = 2)) then
            begin
              WriteLn('Twilio error: ' + reply.IntOf('code') + '  ' + reply.StringOf('message'));
            end;
          Exit;
        end;
      if (parsed <> True) then
        begin
          WriteLn('Expected a JSON response from Twilio.');
          Exit;
        end;
      if (reply.JsonTypeOf('media_list') <> 4) then
        begin
          WriteLn('Expected an array of media items.');
          Exit;
        end;
      count := reply.SizeOfArray('media_list');
      i := 0;
      while (i < count) do
        begin
          reply.I := i;
          mediaSid.SetString(reply.StringOf('media_list[i].sid'));
          if (mediaSid.Length = 0) then
            begin
              WriteLn('Media item is missing its SID.');
              Exit;
            end;
          fileUrl.SetString(mediaBase.GetAsString());
          fileUrl.Append('/');
          fileUrl.AppendSb(mediaSid);
          success := http.HttpNoBody('GET',fileUrl.GetAsString(),fileResp);
          if ((fileResp.StatusCode >= 300) and (fileResp.StatusCode < 400)) then
            begin
              fileUrl.SetString(fileResp.GetHeaderField('Location'));
              if (fileUrl.StartsWith('https://',False) <> True) then
                begin
                  WriteLn('Expected an HTTPS media download URL.');
                  Exit;
                end;
              success := download.HttpNoBody('GET',fileUrl.GetAsString(),fileResp);
            end;
          if ((success <> True) or (fileResp.StatusCode <> 200)) then
            begin
              WriteLn('Media download failed for ' + mediaSid.GetAsString() + '. HTTP ' + fileResp.StatusCode);
              Exit;
            end;
          filename.SetString('mms-media-');
          filename.AppendInt(saved + 1);
          filename.Append('.bin');
          success := fileResp.SaveBodyBinary(filename.GetAsString());
          if (success = False) then
            begin
              WriteLn(fileResp.LastErrorText);
              Exit;
            end;

          WriteLn(filename.GetAsString() + '  ' + mediaSid.GetAsString() + '  ' + reply.StringOf('media_list[i].content_type'));
          saved := saved + 1;
          i := i + 1;
        end;

      if (reply.IsNullOf('next_page_uri') = True) then
        begin
          more := False;
        end
      else
        begin
          url.SetString(reply.StringOf('next_page_uri'));
          if (url.StartsWith('/2010-04-01/Accounts/',True) <> True) then
            begin
              WriteLn('Expected a Twilio relative next-page URI.');
              Exit;
            end;
          url.Prepend('https://api.twilio.com');
        end;
    end;

  WriteLn('Media files saved: ' + saved);


  http.Free;
  url.Free;
  mediaBase.Free;
  download.Free;
  fileResp.Free;
  fileUrl.Free;
  filename.Free;
  mediaSid.Free;
  resp.Free;
  reply.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.