Send SMS with C# and .NET
An async client class on top of HttpClient for .NET 6 or newer. No packages needed.
The client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
public class BudgetSmsException : Exception
{
public string Code { get; } // see the error code list
public BudgetSmsException(string code) : base("BudgetSMS error " + code) => Code = code;
}
public class BudgetSms
{
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(20) };
private const string Base = "https://api.budgetsms.net/";
private readonly string _auth;
public BudgetSms(string username, string userid, string handle)
{
_auth = $"username={Uri.EscapeDataString(username)}&userid={Uri.EscapeDataString(userid)}&handle={Uri.EscapeDataString(handle)}";
}
/// <summary>Calls sendsms, testsms, checkcredit, np, hlr or checksms and returns the text after "OK ".</summary>
public async Task<string> CallAsync(string endpoint, params (string Key, string Value)[] parameters)
{
var query = _auth + string.Concat(parameters.Select(p => $"&{p.Key}={Uri.EscapeDataString(p.Value)}"));
var body = (await Http.GetStringAsync($"{Base}{endpoint}/?{query}")).Trim();
if (!body.StartsWith("OK"))
throw new BudgetSmsException(body.StartsWith("ERR ") ? body[4..] : body);
return body.Length > 3 ? body[3..] : "";
}
}
Send an SMS
var sms = new BudgetSms(Environment.GetEnvironmentVariable("BUDGETSMS_USERNAME")!,
Environment.GetEnvironmentVariable("BUDGETSMS_USERID")!,
Environment.GetEnvironmentVariable("BUDGETSMS_HANDLE")!);
try
{
var result = await sms.CallAsync("sendsms", ("from", "BudgetSMS"), ("to", "31612345678"), ("msg", "Hello from BudgetSMS"));
var smsId = long.Parse(result.Split(' ')[0]); // keep it for the delivery report
Console.WriteLine($"sent, message id {smsId}");
}
catch (BudgetSmsException e)
{
Console.WriteLine($"not sent: {e.Code}");
}
Use "testsms" while developing: same parameters and answer format, but it is a simulator: no SMS is sent and nothing is charged, the message id and price in the answer are random, and about one in five calls returns a random ERR 2xxx so your error handling gets exercised (the destination number is not checked). Add ("price", "1"), ("mccmnc", "1") or ("credit", "1") to get the price and number of parts, the receiver's network or your remaining credit after the message id.
Credit, number lookup and delivery status
var credit = decimal.Parse(await sms.CallAsync("checkcredit"), System.Globalization.CultureInfo.InvariantCulture); // 123.4550
var network = (await sms.CallAsync("np", ("to", "31612345678"))).Split(' '); // ["204", "08", "0.0640"]
var status = int.Parse(await sms.CallAsync("checksms", ("smsid", "64354593"))); // 1 = delivered; see the DLR status list
Receive delivery reports (Push DLR) in ASP.NET Core
Enter the URL of this endpoint in the control panel under Push DLR; we call it with GET on every status update.
app.MapGet("/dlr", (long id, int status, long date) =>
{
// id = message id from the sendsms response, status 1 = delivered, 2 and 3 = failed (full list: DLR status),
// date = unix timestamp. Update your own records here.
return Results.Ok("OK");
});