Sending SMS in C# (.NET): Integration with SMS Service APIs

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Sending SMS in C# (.NET): Complete Guide to API Integration



In the modern world, SMS notifications remain one of the most reliable ways to communicate with users. In the C# (.NET) ecosystem, there are many approaches to sending messages — from direct HTTP requests to using specialized NuGet packages. In this article, we will explore how to set up SMS sending through popular services (Twilio, sms.ru, Smsc) using a pure HttpClient implementation, as well as look at a ready-made library for working with Russian providers.



Choosing an Approach: Library or Pure HTTP?

There are two main ways to send SMS in C#:

  • Using the official SDK (e.g., Twilio for .NET) — provides a typed interface, built-in error handling, and documentation.
  • Direct work with REST API via HttpClient — full control over the request, minimal dependencies, ability to work with any provider.

The second option is preferable for educational purposes and projects requiring flexibility. Let's examine it in detail.



Basic Implementation of Sending SMS via HTTP API

Let's create a class SmsService that will send messages via the sms.ru API (or any other service with a similar format).



using System;using System.Net.Http;using System.Threading.Tasks;

public class SmsService{ private readonly HttpClient _httpClient; private readonly string _apiKey;

public SmsService(string apiKey) { _httpClient = new HttpClient(); _apiKey = apiKey; }

public async Task<string> SendSmsAsync(string phone, string message) { var url = $"https://sms.ru/sms/send?api_id={_apiKey}&to={phone}&msg={Uri.EscapeDataString(message)}&json=1"; var response = await _httpClient.GetAsync(url); return await response.Content.ReadAsStringAsync(); }}


Usage:

var sms = new SmsService("YOUR_API_KEY");string result = await sms.SendSmsAsync("+79123456789", "Hello! This is a test message.");Console.WriteLine(result);


Optimization: Asynchrony and Error Handling

In a real project, you need to add number validation, retry attempts on failures, and logging. Improved version:



public async Task<SmsResult> SendSmsAsync(string phone, string message){    try    {        if (string.IsNullOrWhiteSpace(phone) || phone.Length < 10)            return new SmsResult { Success = false, Error = "Invalid phone number format" };

var url = $"https://sms.ru/sms/send?api_id={_apiKey}&to={phone}&msg={Uri.EscapeDataString(message)}&json=1"; var response = await _httpClient.GetAsync(url); var json = await response.Content.ReadAsStringAsync();

// Parse JSON (can use System.Text.Json) var result = JsonSerializer.Deserialize<SmsApiResponse>(json); return new SmsResult { Success = result?.Status == "OK", Response = json }; } catch (HttpRequestException ex) { return new SmsResult { Success = false, Error = $"Network error: {ex.Message}" }; }}


Create a simple model for parsing the response:

public class SmsApiResponse{    public string Status { get; set; }    public int Balance { get; set; }}


Ready-Made Library: Twilio for .NET

If you need production readiness, use the Twilio SDK (NuGet: Twilio). Example:



using Twilio;using Twilio.Rest.Api.V2010.Account;

TwilioClient.Init("ACCOUNT_SID", "AUTH_TOKEN");

var message = MessageResource.Create( body: "Hello from C#!", from: new PhoneNumber("+1234567890"), to: new PhoneNumber("+79123456789"));

Console.WriteL

Recommendations