Send automated messages on WhatsApp using C# (.NET)
For developers and companies, efficient communication is crucial. Automate your WhatsApp messages using Wassenger and C# to streamline operations and ensure every message is delivered promptly. With this integration, you can:
- Schedule and send personalized messages: Keep your customers informed with timely updates, reminders, and promotional offers.
- Track message delivery and responses: Monitor the effectiveness of your communication and make data-driven decisions.
- Reduce manual workload: Free up your team’s time by automating routine messages, allowing them to focus on more strategic tasks.
- Enhance customer experience: Provide consistent and reliable communication, improving customer satisfaction and loyalty.
Dive into our guide to learn how to implement this solution and revolutionize your communication strategy with Wassenger and C#.
🫣 Don’t want to use programming? No problem! Explore our new no-code WhatsApp Campaigns feature. Import your contacts, define a message, set a delivery date and relax! 🥳 🥳
🤩 🤖 Wassenger is a complete communication platform and API solution for WhatsApp. Explore more than 100+ API use cases and automate anything on WhatsApp by signing up for a free trial and getting started in minutes!
Requirements
- To have a WhatsApp number already linked to the platform and online.
- Message recipient phone number with international prefix in E164 format. Example:
+12345678900
. Validate the phone number format here.
API endpoint
We will use the following API endpoint to send messages to a group:
Prepare the request
Target API URL using the POST method
https://api.wassenger.com/v1/messages
Required HTTPS headers > Obtain your API key here
Content-Type: application/json
Token: $API_TOKEN
Use body in JSON format
{
"phone": "+1234567890",
"message": "Hello world, this is a sample message"
}
🖥️ Looking for a code example? Go to the API live tester and get ready-to-use code examples in 15+ programming languages, including Python, JavaScript, PHP, C#, Java, Ruby, Go, Powershell, cURL and more.
🤩 🤖 Wassenger is a complete API solution for WhatsApp. Sign up for a 7-day free trial and get started in minutes!
Send automated messages with C# (RestClient)
- Setup: The API key, phone number, and message are stored in variables for easy modification.
- RestClient and RestRequest: The
RestClient
is initialized with the API URL, and theRestRequest
is created with the POST method. - Headers: Headers for
Content-Type
andToken
are added to the request. - Payload: The payload is created as an anonymous object and added to the request body using
AddJsonBody
. - Execution and Handling: The request is executed using the
Execute
method, and the response is checked for success. Appropriate messages are printed based on the response status.
// This code requires you to have installed RestSharp package.
// Documentation: https://restsharp.dev
// Installation: https://www.nuget.org/packages/RestSharp
using System;
using RestSharp;
class Program
{
static void Main(string[] args)
{
var apiKey = "YOUR_ACTUAL_API_KEY";
var phone = "+1234567890";
var message = "Hello world, this is a sample message";
var client = new RestClient("https://api.wassenger.com/v1/messages");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Token", apiKey);
var payload = new
{
phone = phone,
message = message
};
request.AddJsonBody(payload);
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
Console.WriteLine("Message sent successfully.");
Console.WriteLine("Response: " + response.Content);
}
else
{
Console.WriteLine("Failed to send message. Status code: " + response.StatusCode);
Console.WriteLine("Error: " + response.ErrorMessage);
}
}
}
Send automated messages with C# (HttpClient)
- Setup: The API key, phone number, and message are stored in variables.
- HttpClient and HttpRequestMessage: The
HttpClient
instance is created, andHttpRequestMessage
is initialized with the POST method and the API URL. - Headers: The
Token
header is added to the request. - Content: The request content is created using
StringContent
the JSON payload and appropriate content type. - Execution and Handling: The request is sent asynchronously using
SendAsync
. The response is checked for success usingEnsureSuccessStatusCode
. Any exceptions are caught and handled, with appropriate error messages displayed.
// This code uses the built-in HttpClient package in the .NET framework.
// Documentation: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var apiKey = "YOUR_ACTUAL_API_KEY";
var phone = "+1234567890";
var message = "Hello world, this is a sample message";
using (var client = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://api.wassenger.com/v1/messages"),
Headers =
{
{ "Token", apiKey },
},
Content = new StringContent($"{{\"phone\":\"{phone}\",\"message\":\"{message}\"}}", Encoding.UTF8, "application/json")
};
try
{
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Message sent successfully.");
Console.WriteLine("Response: " + responseBody);
}
}
catch (HttpRequestException httpEx)
{
Console.WriteLine($"HTTP error occurred: {httpEx.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
}
Live API testing
You can live-test and play with the API directly from your browser.
Once you are done testing, get the auto-generated code example in your preferred programming language and you will be ready to go.
FAQ
What are the differences between using RestClient and HttpClient for this purpose?
To send automated messages in C#, you can use either the RestClient from the RestSharp package or the built-in HttpClient from the .NET framework.
- RestClient (RestSharp): This third-party library simplifies making RESTful API calls. It’s user-friendly and great for quick setups, abstracting much of the complexity.
- HttpClient: This built-in class offers more control and flexibility. It is ideal for more complex scenarios and better performance optimization but requires more boilerplate code.
Choose RestClient for simplicity and ease of use, and HttpClient for greater control and performance.
How to send messages to multiple phone numbers
You just have to send multiple API requests, one per target phone number.
For instance, if you want to send a message to 10 phone numbers, you should send 10 independent HTTPS requests to the API.
There is no option to send multiple messages in a single API request.
How to validate if a phone number can receive WhatsApp messages
You can validate if a given phone number is linked to a WhatsApp account and can receive messages.
The API provides an endpoint that can validate whether a given phone number exists in WhatsApp or not.
The only requirement is to have at least one WhatsApp number connected to the platform in your current account.
For more details, please check out the API endpoint documentation here.
Before you check if a phone number exists on WhatsApp, you can also validate and normalize the format of a list of phone numbers by using the numbers validator API endpoint. This endpoint only validates the correct E164 format, but it does not check whether the phone number effectively exists on WhatsApp.
Note: The number of WhatsApp check validations is limited per month based on your subscription plan. Please check out the pricing table for more details about the limits.
Looking for more answers? Check out the extended FAQs.
Further useful resources
API Documentation
For more details about the endpoint API, please check the documentation where you will find all the details about the accepted request params, possible success or error responses and ready-to-use code examples in multiple programming languages:
https://app.wassenger.com/docs/#tag/Messages/operation/createMessage