Search code examples
c#asp.nettwilio-api

How to download MMS Media from Twilio using the .NET SDK


I have a project that my team is working on to send and receive Twilio MMS Messages. We have used the Twilio Client in the C# SDK for years to successfully send messages. Now with this project, it is clear how to determine there are Media files sent with the MMS Message and locate them, but we need some help downloading them.

I am aware that we can write the code in C# and add the necessary authentication, but I was hoping to keep all our activities within the Twilio SDK and client so the code is easily accessible to pick up by any of our current or potential future developers. Is there a way to download a file through the Twilio client? I didn't see any examples in the docs.


Solution

  • The Twilio SDK can help you locate the media of MMS messages, and information about the media is also passed into your webhook handlers. However, the SDK doesn't have any classes/methods to help you download the media files.

    By default, the file is publicly accessible if you know the URL, and doesn't require authentication. You can enable basic auth for your MMS media files so only you can download them by authenticating with your Account SID and Auth Token or API Key SID and API Key Secret.

    Here's a C# sample on how to do download the file with and without basic auth:

    using System.Net.Http.Headers;
    using System.Text;
    
    const string accountSid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    const string messageSid = "MMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    const string mediaSid = "MExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    var mediaUrl = $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Messages/{messageSid}/Media/{mediaSid}";
    const string localFilePath = "image.jpg";
    
    using var httpClient = new HttpClient();
    using var httpRequest = new HttpRequestMessage
    {
        Method = HttpMethod.Get,
        RequestUri = new Uri(mediaUrl)
    };
    
    const bool useBasicAuth = true;
    if (useBasicAuth)
    {
        var authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
        var authHeaderValue = $"{accountSid}:{authToken}";
        authHeaderValue = Convert.ToBase64String(Encoding.ASCII.GetBytes(authHeaderValue));
        httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
    }
    
    using var response = await httpClient.SendAsync(httpRequest);
    
    if (!response.IsSuccessStatusCode)
    {
        Console.WriteLine($"HTTP Status Code: {response.StatusCode}");
        Console.WriteLine($"Response body: {await response.Content.ReadAsStringAsync()}");
        return;
    }
    
    await using var fileStream = new FileStream(localFilePath, FileMode.CreateNew);
    await response.Content.CopyToAsync(fileStream);