How to send an SMS text message in C#

This example finishes the series showing how to make a C# program send an SMS (Short Message Service) message. You could use this technique to make a program monitor some sort of ongoing process and send you a message if there is a problem.

The example How to extract only some of the information from a JSON file in C# demonstrates how you can download a JSON file that contains information about SMS gateway email addresses and extract the carrier and email information. The example How to send an email message in C# shows how to send an email.

This example combines the techniques demonstrated in those examples to send an SMS message.

When the program starts, it uses the techniques demonstrates by the first example to get the SMS carrier information.

The program executes the following code when you fill in the information and click Send.


// Send the message.
private void btnSend_Click(object sender, EventArgs e)
{
    try
    {
        string carrier_email = cboEmail.SelectedItem.ToString();
        string phone = txtPhone.Text.Trim().Replace("-", "");
        phone = phone.Replace("(", "").Replace(")", "").Replace("+", "");
        string to_email = phone + "@" + carrier_email;

        SendEmail(txtToName.Text, to_email,
            txtFromName.Text, txtFromEmail.Text,
            txtHost.Text, int.Parse(txtPort.Text),
            chkEnableSSL.Checked, txtPassword.Text,
            txtSubject.Text, txtBody.Text);

        MessageBox.Show("Message sent");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

The program first gets the SMS carrier's email address from the cboEmail ComboBox. The email address the program uses must not contain any characters other than digits so the code trims the address to remove spaces. It also removes the -, (, ), and + characters.

Next the code appends the @ symbol and the carrier's SMS gateway email address. The result should look something like this:

    [email protected]

The program finishes by calling the SendEmail method described in the second post mentioned above to send the message to this email address.

That's all there is to it! The tools you need to download the JSON carrier data, parse the data, and send the email message are somewhat involved. Once you've built those tools, however, sending the SMS message is comparatively easy.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.