C# SEND From Database

By
C# Code Example - Sending SMS from Database

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class Program
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task SendSMS(string senderId, string recipient, string messageText)
    {
        string apiUrl = "https://rest.sendmode.com/v2/send";
        string apiKey = "YOUR_ACCESS_KEY";

        var message = new
        {
            messagetext = messageText,
            senderid = senderId,
            recipients = new[] { recipient }
        };

        var jsonMessage = JsonConvert.SerializeObject(message);
        var content = new StringContent($"message={jsonMessage}", Encoding.UTF8, "application/x-www-form-urlencoded");

        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Add("Authorization", apiKey);

        HttpResponseMessage response = await client.PostAsync(apiUrl, content);
        string responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine($"SMS sent to {recipient}: {responseBody}");
    }

    public static async Task Main(string[] args)
    {
        string connectionString = "YourConnectionStringHere";
        string storedProcedureName = "YourStoredProcedureName";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand(storedProcedureName, connection))
            {
                command.CommandType = CommandType.StoredProcedure;

                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string mobileNumber = reader["MobileNumber"].ToString();
                        string firstName = reader["FirstName"].ToString();
                        string message = $"Hi {firstName}, your personalized message content here.";

                        await SendSMS("YourSenderID", mobileNumber, message);
                    }
                }
            }
        }
    }
}