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

Delphi ActiveX
var
success: Integer;
http: TChilkatHttp;
url: TChilkatStringBuilder;
mediaBase: TChilkatStringBuilder;
download: TChilkatHttp;
fileResp: TChilkatHttpResponse;
fileUrl: TChilkatStringBuilder;
filename: TChilkatStringBuilder;
mediaSid: TChilkatStringBuilder;
saved: Integer;
resp: TChilkatHttpResponse;
reply: TChilkatJsonObject;
more: Integer;
parsed: Integer;
count: Integer;
i: Integer;

begin
success := 0;

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

url := TChilkatStringBuilder.Create(Self);
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 := TChilkatStringBuilder.Create(Self);
mediaBase.AppendSb(url.ControlInterface);
url.Append('.json');
//  Handle the API redirect explicitly so a signed download uses no Twilio credentials.
http.FollowRedirects := 0;
download := TChilkatHttp.Create(Self);
download.RequireSslCertVerify := 1;
fileResp := TChilkatHttpResponse.Create(Self);
fileUrl := TChilkatStringBuilder.Create(Self);
filename := TChilkatStringBuilder.Create(Self);
mediaSid := TChilkatStringBuilder.Create(Self);
saved := 0;
resp := TChilkatHttpResponse.Create(Self);
reply := TChilkatJsonObject.Create(Self);

more := 1;
while (more = 1) do
  begin
    success := http.HttpNoBody('GET',url.GetAsString(),resp.ControlInterface);
    if (resp.StatusCode = 0) then
      begin
        Memo1.Lines.Add('No HTTP response from Twilio.');
        Exit;
      end;
    parsed := reply.Load(resp.BodyStr);
    if ((success <> 1) or (resp.StatusCode <> 200)) then
      begin
        Memo1.Lines.Add('Twilio returned HTTP ' + IntToStr(resp.StatusCode));
        if ((parsed = 1) and (reply.JsonTypeOf('code') = 2)) then
          begin
            Memo1.Lines.Add('Twilio error: ' + IntToStr(reply.IntOf('code')) + '  ' + reply.StringOf('message'));
          end;
        Exit;
      end;
    if (parsed <> 1) then
      begin
        Memo1.Lines.Add('Expected a JSON response from Twilio.');
        Exit;
      end;
    if (reply.JsonTypeOf('media_list') <> 4) then
      begin
        Memo1.Lines.Add('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
            Memo1.Lines.Add('Media item is missing its SID.');
            Exit;
          end;
        fileUrl.SetString(mediaBase.GetAsString());
        fileUrl.Append('/');
        fileUrl.AppendSb(mediaSid.ControlInterface);
        success := http.HttpNoBody('GET',fileUrl.GetAsString(),fileResp.ControlInterface);
        if ((fileResp.StatusCode >= 300) and (fileResp.StatusCode < 400)) then
          begin
            fileUrl.SetString(fileResp.GetHeaderField('Location'));
            if (fileUrl.StartsWith('https://',0) <> 1) then
              begin
                Memo1.Lines.Add('Expected an HTTPS media download URL.');
                Exit;
              end;
            success := download.HttpNoBody('GET',fileUrl.GetAsString(),fileResp.ControlInterface);
          end;
        if ((success <> 1) or (fileResp.StatusCode <> 200)) then
          begin
            Memo1.Lines.Add('Media download failed for ' + mediaSid.GetAsString() + '. HTTP ' + IntToStr(fileResp.StatusCode));
            Exit;
          end;
        filename.SetString('mms-media-');
        filename.AppendInt(saved + 1);
        filename.Append('.bin');
        success := fileResp.SaveBodyBinary(filename.GetAsString());
        if (success = 0) then
          begin
            Memo1.Lines.Add(fileResp.LastErrorText);
            Exit;
          end;

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

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

Memo1.Lines.Add('Media files saved: ' + IntToStr(saved));