Hi everyone, today I’d like to show you how easy it is to send text messages in C#. As controls engineers and PLC programmers we are building, deploying and relying on software-based solutions to monitor critical systems. Implementing an automated SMS text-based notification system into your next SCADA or HMI project is a logical next step.
To allow your applications to send text messages in C#, you are going to need a platform or API that will allow your solutions to handle the underlying logistics of SMS communication. By far the best solution I have found is a service called Twilio.
Simply put, Twilio is a developer platform that provides a set of REST APIs for communications. These APIs are designed to give your custom C# solutions the engine it needs to send and receive SMS text messages, as well as a whole host of other functionality outside the scope of this article.
I’ve used the Twilio Service and APIs on countless projects, and I have to tell you, it is the most reliable I’ve ever used by far.
So how do you send text messages in C#? To answer this question we are going to break the article down into the following three easy-to-follow sections:
- Signing up for Twilio and Getting a phone number.
- Getting the required Twilio APIs into Visual Studio.
- Setting up your C# application to send your first text message.
Signing Up for Twilio and Getting a Phone Number
Before your C# applications can send text messages, you’ll need to sign up for a Twilio account. The nice thing about the Twilio service is they do provide your with a free trial so your can test their service out. This is a very useful feature, however, there are some limitations.
Basically, when you create a trial account they will set you up with a temporary phone number and credit your account with a small amount of money so you can test their service. For sending SMS and MMS messages, their are two primary limitations:
- When you send an SMS from your free trial phone number, it will always begin with “Sent from a Twilio trial account.” They remove this message after you upgrade to the full account.
- While in trial mode, you can only send messages to non-Twilio phone numbers you’ve verified with Twilio at account setup.
Once you’re satisfied with the service you’ll need to upgrade your account to the full account and buy a permanent phone number at $1.00/month.
To buy a phone number visit their Buy a Number page inside your account. Be sure to check the country that you’re targeting and check the SMS box.
Then click Search and it will generate a list of available numbers with their capabilities. Just be sure the number you choose is SMS capable.
Getting the required Twilio APIs into Visual Studio
Of course, you’re going to need to have Visual Studio already installed. If you’re reading this article then I’m going to assume that you have that bit done.
Open Visual Studio and create a new Windows Forms App project.
Then navigate to Tools –> Nuget Package Manager –> Package Manager Console. Once the console is open type at the prompt PM> Install-Package Twilio
This will install the required Twilio REST API for you. Your Visual Studio project is now ready to send text messages in C#.
Setting up your C# application to send your first text message
Below is a snippet of code from an actual project currently running in production at a large parts manufacturing plant. Basically, the application monitors various water reclaim systems for fault and deviation alarms.
In total, there are four water reclaims that are spread out across two facilities. Each reclaim system is controlled by an Allen Bradley SLC 5/05 with embedded Ethernet in the processor. The application, or more appropriately, the Windows Service, monitors all these controllers for fault conditions from a central server.
In the event of a fault, or deviation from established setpoints, the SMSMailer class below is instantiated and a text message is sent to the appropriate personnel that should respond to implement corrective action.
Below is the class I’ve created called SMSMailer that handles how to send text messages in C#.
While there appears to be a lot to digest here, I assure you it is quite straight forward. To simplify, let’s look at each individual code block together to go over what it is, and why it’s important.
Step #1 – Importing the Twilio APIs
The first thing you need to do to start using Twilio in your project is import the necessary libraries with the using statement.
This allows you to make full use of the different objects, classes and methods that Twilio offers.
Step #2 – Setting up your Account SID and Authorization Token
Now that you have the necessary Twilio libraries imported to your class, you can send text messages in C# by leveraging the phone number you purchased (or are trialing) with a single API request.
After you sign up for a Twilio account and create a project, there will be two key pieces of information that you’ll need:
- Account SID
- Authorization Token
You can view both of these from the main dashboard of your account:
Of course, this information is sensitive, this is why these fields are blurred and protected. Once you acquire these two pieces of information, it’s time to initialize it in our code.
You can see I’ve declared both accountSid and authToken as a constant. Then, once the class is instantiated the default constructor, SMSMailer(), is called which initializes TwilioClient.Init() with the information.
Step #3 – SendMessage() methods
You will see from the full class image above that I have two SendMessage() methods. Let’s cover the first one, then we’ll move on to the second. In C# when you have multiple methods with the same name this is known as overloading.
For the first SendMessage() method (overload #1), you can see takes in several parameters, namely:
- string FromNumber – this is the paid Twilio Phone Number you are using.
- string ToNumber – this is the (single) cell number (or recipient) you are sending to.
- string Location – this is the location/machine the fault originated.
- string FaultDescription – the description of the fault that was generated.
For the second SendMessage() method (overload #2), you can see it takes in similar parameters, with the exception of one of them, namely:
- List<string>ToNumbers – a list of cell phone numbers (recipients) you are sending to. This allows you to notify multiple people at the same time (covered in detail in Step #5).
You can see that the body of both methods is largely the same, with the exception of the overload #2 method which uses a for loop to iterate over the list of recipients to send multiple notifications. Let’s examine the body of these methods further.
Step #4 – The Body of the SendMessage() methods
We’ve defined the public facing SendMessage() overload methods that we’ll be using in step #3 above. And I think we’ve successfully explained the primary difference between the two overloads. Now let’s look closer at the body of these methods where we begin to construct the message we are going to send to the SMS recipients.
You can see we can leverage the Twilio API method call to MessageResource.Create(). This method takes on 3 parameters, namely, body: from: and to:. Let’s explain how we populate each of these parameters:
- body: it should be clear that I have another private method in this SMSMailer() class called buildMessageBody() that takes two parameters, namely, string location, string faultDescription.
You can see this is where we unload the lifting involved in composing and formatting the actual SMS text message we are going to send. I make use of the DateTime.Now to timestamp the time of the fault and Environment.NewLine to handle the formatting of the message.
- from: this is just another Twilio API call that accepts the FromNumber being passed into the SendMessage() method.
- to: this is just another API call to the Twilio library that accepts the ToNumber, or iterates over the list of the ToNumbers being passed into the SendMessage() method depending on which overload you call.
The last thing I need to show you is how I accomplished the task of generating the List of numbers for the second overload method call.
Step #5 – Creating the List<string> of multiple recipients
As explained above, the second SendMessage() overload method takes a List<string> of numbers so you can send notifications to multiple people in one fell swoop. Let’s quickly look at that specific method again.
As you can see, as far as the body is concerned, it is exactly the same as the first SendMessage() method. Except this time we’re passing in a List<string> of numbers and wrapping the body up in a for loop. The loop will iterate over the entire list of numbers generating a message and sending a text message to each recipient in the List<string>.
Below is the class created to handle the List<string> construction. I’m calling it SMSRecipients, for demonstration purposes, and to keep things simple, I’ve just gone ahead and hard-coded the fake phone numbers in the list that will be the recipients of the automatic SMS text notification.
You can see I’m making use of the C# built-in System.Collection.Generic to build my list of SMS text message recipients. I build the list of recipients in the default constructor then setup a public accessor method, GetList(), that returns the list.
Since the list is not likely to change (often), I’ve declare it as a Static class so instantiation is not needed, just a call to the SMSRecipients.GetList() whenever you would like to make use of the list.
And that’s it!!! Now we’ve built a way to not only send text messages in C# to a single person, but also to multiple persons in one shot.
How to send text messages in C# – Final words…
Well I hope you found some useful information this article. Twilio is truly a great service to SMS enable your custom C# applications. Adding automatic notification to you SCADA or HMI apps is a great feature that your customers will love.
If you enjoyed this article, consider checking out some of my other articles below:
- Best 3D Printers Under $500: Ultimate Buyer’s Guide
- What is Industrial Automation? Industry 4.0?
- Best Oscilloscopes Under $500: Expert Reviews
- What is a Thermocouple? Cold Junction Compensation?
- Best Desktops for Programming (PLC, CAD, OOP)
- How To Become A PLC Programmer
- Best Laptops For PLC Programming
While you’re here, consider registering with the site and become a PLCGurus.NET member. Registration is completely free!