This guide shows how to send SMS with the ESP32 using an online service called Twilio. With this service, you can send SMS with the ESP32 without needing a GSM module or a dedicated physical SIM card. Using Twilio is not free but you can sign up for a free trial for testing purposes. We’ll use a free trial account throughout the tutorial.
You can send SMS with the ESP32 without the need to rely on third-party services if you have a GSM module and a dedicated SIM card. We have tutorials showing how to send SMS with the ESP32 using the SIM800L and SIM7000G modules:
- ESP32 SIM800L: Send Text Messages (SMS Alert) with Sensor Readings
- LILYGO T-SIM7000G ESP32: Connect to the Internet, Send SMS, and Get GPS Data
If you’re looking for different types of notifications and alerts with the ESP32, you can check the following tutorials:
- How to send emails with the ESP32?
- Send WhatsApp messages with the ESP32
- Telegram: ESP32 Motion Detection with Notifications (Arduino IDE)
Introducing Twilio
Twilio provides programmable communication tools for making and receiving phone calls, sending and receiving text messages, and performing other communication functions using its web service APIs. Throughout this tutorial, we’ll use their programmable messaging services.
Twilio is a paid service, but you can sign-up for a free account for testing purposes. Then, if their services are useful for your specific project, you can always upgrade your account later on. We’ll use a free trial account throughout this tutorial.
Creating a Free Trial Account
Go to https://www.twilio.com/ and click on Sign up and start building.
Enter your details and get started with a free trial.
Set Up the Free Twilio Trial Account
There are some steps you need to follow to set up your free Twilio trial account. We’ll describe the steps you need to follow in the present tutorial. You can also check Twilio’s official instructions here.
Verify your personal phone number
When you sign up for your free trial account, you verified your personal phone number. It should be on the list of verified phone numbers on your dashboard: Phone Numbers > Manage > Verified Caller IDs.
Verify other recipient numbers
When using the free trial account, you must verify all numbers that you’ll want to send an SMS. When verifying the numbers, you’ll get an SMS with a verification code that you need to insert. So, you need to have physical access to those numbers. This is not needed on the paid account.
On that previous menu (Phone Numbers > Manage > Verified Caller IDs), click on Add new Called ID to add a new verified number. You’ll receive an SMS with a verification code on that number.
Get a Twilio Phone Number
To send messages using Twilio, you’ll need to purchase a Twilio phone number. At the time of writing this tutorial, when I signed up for the free account, I got a $15.50 credit, which is enough to get a phone number and test sending some SMS.
On your dashboard, on the left sidebar, go to Phone Numbers > Manage > Buy a number. You’ll see a list of available numbers. Make sure you select SMS on the number capabilities. You can also select the country.
Note: I tried purchasing a number from my country (Portugal), but I needed to fill out a regulatory bundle and submit some documents for review. So I ended up buying a card from the US instead, which didn’t require any of that and was ten times cheaper. This works for testing purposes, once you decide to move for a more permanent solution, double-check if that number is the most suitable for your case scenario.
Once you’ve chosen a phone number click on the Buy button.
Programmable Messaging – Get Set Up
Now, you have everything set up to start creating a programmable messaging service. On your dashboard, on the left sidebar click on Messaging > Try it out > Get Set Up. Then, click on Start set up.
Give a name to the Messaging Service, for example, ESP32 Alerts and click on Create Messaging Service.
Then, select the Twilio phone number you created previously and click on Add this number.
After that, the programmable messaging service will be all set up. You’ll get access to your account information: account SID and Auth token. You’ll need them later in the ESP32 code.
You can test if everything is working as expected by clicking on Try SMS. You’ll see a similar page as shown below. Enter the phone number you want to send the message to (it must be a verified number—see this previous section), select the messaging service you created previously, and write some body text and click on Send test SMS.
After a few seconds, you should receive the test SMS on the selected number.
All SMS sent from a Twilio trial account will have the text: “Sent from your Twilio trial account”. This text doesn’t show up on premium accounts.
ESP32: Send SMS using Twilio
Sending SMS using Twilio is very straightforward thanks to its API. You can read the SMS API documentation. You simply make HTTP requests with the ESP32 with the right parameters (accordingly to Twilio’s API) to send SMS. You can check this tutorial about HTTP requests with the ESP32.
Or you can use a library that takes care of all that, and you just need to insert your Twilio account details and the SMS body text. Throughout this tutorial, we’ll use a library called twilio-esp32-client.
Installing the twilio-esp32-client Library
The twilio-esp32-client library can be installed through the Arduino IDE Library Manager. Go to Sketch > Include Library > Manage Libraries. Search for twilio-esp32-client and install the library.
ESP32 Send SMS using Twilio – Code
Sending code using Twilio using the twilio-esp32-client library is very straightforward. First, you need to create a Twilio instance, and then you just need to call the send_message() method and pass as arguments your Twilio account details, sender and recipient numbers, and the message body. The following code is an example from the library’s examples folder.
/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/send-sms-esp32-twilio/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*********/
// Library example: https://github.com/ademuri/twilio-esp32-client
#include "twilio.hpp"
// Set these - but DON'T push them to GitHub!
static const char *ssid = "REPLACE_WITH_YOUR_SSID";
static const char *password = "REPLACE_WITH_YOUR_PASSWORD";
// Values from Twilio (find them on the dashboard)
static const char *account_sid = "REPLACE_WITH_YOUR_ACCOUNT_SID";
static const char *auth_token = "REPLACE_WITH_YOUR_ACCOUNT_AUTH_TOKEN";
// Phone number should start with "+<countrycode>"
static const char *from_number = "REPLACE_WITH_TWILIO_NUMBER";
// You choose!
// Phone number should start with "+<countrycode>"
static const char *to_number = "REPLACE_WITH_RECIPIENT_NUMBER";
static const char *message = "Hello from my ESP32 (via twilio)";
Twilio *twilio;
void setup() {
Serial.begin(115200);
Serial.print("Connecting to WiFi network ;");
Serial.print(ssid);
Serial.println("'...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.println("Connecting...");
delay(500);
}
Serial.println("Connected!");
twilio = new Twilio(account_sid, auth_token);
delay(1000);
String response;
bool success = twilio->send_message(to_number, from_number, message, response);
if (success) {
Serial.println("Sent message successfully!");
} else {
Serial.println(response);
}
}
void loop() {
}
How the Code Works
Start by including the twilio-esp32-client library.
#include "twilio.hpp"
Insert your network credentials on the following lines:
static const char *ssid = "REPLACE_WITH_YOUR_SSID";
static const char *password = "REPLACE_WITH_YOUR_PASSWORD";
Insert your Twilio account details: the account SID and token, and the Twilio phone number.
static const char *account_sid = "REPLACE_WITH_YOUR_ACCOUNT_SSID";
static const char *auth_token = "REPLACE_WITH_YOUR_ACCOUNT_AUTH_TOKEN";
// Phone number should start with "+<countrycode>"
static const char *from_number = "REPLACE_WITH_TWILIO_PHONE_NUMBER";
Insert the recipient number and the message.
// Phone number should start with "+<countrycode>"
static const char *to_number = "INSERT_RECIPIENT_NUMBER";
static const char *message = "Hello from my ESP32 (via twilio)";
If you’re using a free trial account, the recipient number must be on the list of the Verified caller IDs.
Create a Twilio pointer variable called twilio.
Twilio *twilio;
In the setup(), initialize the Serial Monitor and connect the ESP32 to your local network so that it can get access to the internet and make the HTTP requests to send SMS.
Serial.begin(115200);
Serial.print("Connecting to WiFi network ;");
Serial.print(ssid);
Serial.println("'...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.println("Connecting...");
delay(500);
}
Serial.println("Connected!");
The following line instantiates a new Twilio instance with the account details:
twilio = new Twilio(account_sid, auth_token);
Then call the send_message() function that accepts as arguments the recipient number, the sender number, the message, and a variable to hold the response. This function makes an HTTP request in the background with all the necessary parameters to Twilio API to send SMS.
String response;
bool success = twilio->send_message(to_number, from_number, message, response);
if (success) {
Serial.println("Sent message successfully!");
} else {
Serial.println(response);
}
}
This function will return true if the message is successfully sent or the response of the HTTP request in case it fails.
Sending an SMS is not free and it will be deducted from the credit on your Twilio account. So, we’re just sending one SMS on the setup() when the board starts. The idea is to apply this sample code to your own project.
The loop() is empty.
void loop() {
}
Demonstration
After inserting all the required details, you can upload the code to your ESP32 board. Select an ESP32 board in Tools > Board and select the COM port in Tools > Port. Then, click on the Upload button.
After uploading, open the Serial Monitor at a baud rate of 115200. Press the ESP32 RST button to restart the board. If everything goes as expected, you should receive a similar message as shown below.
After a few seconds, you should receive an SMS from Twilio on your phone.
Wrapping Up
In this tutorial, you learned how to send SMS with the ESP32 using Twilio programmable messaging API. The advantage of using this method is that you don’t need to have a modem or a physical SIM card to send SMS with your board.
However, you need to buy a Twilio phone number, and you’ll need to pay a monthly subscription for the card. You’ll also need to pay for each SMS you send. You can sign up for a free trial account that gives you credit to experiment with Twilio in your projects—so, you can try their services for a while for free. If you feel their service is the right for your projects, then you can update your account later on.
You can also send SMS with the ESP32 using other methods—using modems like the SIM800L, SIM7000G, and others. We have tutorials showing how to send SMS with the ESP32 using the SIM800L and SIM7000G modules:
- ESP32 SIM800L: Send Text Messages (SMS Alert) with Sensor Readings
- LILYGO T-SIM7000G ESP32: Connect to the Internet, Send SMS, and Get GPS Data
We hope you find this tutorial useful.
Thanks for reading.
Hi Sara, great tutorial (like all your other nice work)!
Thank you for all your time & dedication to inspire people to use ESP!
Enjoy the upcoming holidays and keep up the good work in 2023!
SS
Thank you.
I wish you a great holiday season too.
Regards,
Sara
Hi Sara,
you can also write a tutorial about receiving SMS write with twilio.
OL
Hi.
Thanks for the suggestion.
I’ll take a look at that.
Regards,
Sara
Hi Sara, great tutorial as always.
I would like to ask, how much does it cost to send an sms from your US twilio number to a portugease mobile number? I couldn’t find such information on the twilio site. And also, can twilio receive sms from your portuguese mobile and forward them to the ESP32 for processing? Is this possible?
Hi.
I’m sorry, but I don’t remember the price per SMS.
I think its better to contact their support to get more detailed information.
Yes, the US number can send SMS to a Portuguese number – I tested it.
Yes, it can receive SMS and forward them to the ESP32 (however I didn’t test this scenario).
Regards,
Sara
Hello and thanks for all your awesome tutorials!!!
Can this tutorial be modified to run on a esp8266
Thanks
Hi.
Yes.
But for some reason, I had issues trying this on an ESP8266. That’s why we don’t have a tutorial for the ESP8266.
You can try taking a look at twilio documentation for the ESP8266: https://www.twilio.com/docs/sms/tutorials/how-to-send-sms-messages-esp8266-cpp
I hope this helps.
Regards,
Sara
it would be interesting to integrate esp32cam to send a picture…
We have something like that, but with Telegram: https://randomnerdtutorials.com/telegram-esp32-cam-photo-arduino/
Regards,
Sara
1) Nice that this tutorial is all-in-one. 2) Can “message” not be static, ie char message[40]; , and fill it in “on the fly” ? 3) How about “to_number” (assuming I only use numbers that I’d told Twillio about during signup) ?
Re “you’ll need to pay a monthly subscription for the card”: is this real ? Does it refer to a SIM card from a different article ?
Hi.
You need to pay for a subscription for your Twilio SIM card.
Learn more here: https://www.twilio.com/en-us/iot/super-sim-card-pricing
Regards,
Sara
This is about the “send-sms-esp32” article. There’s no SIM card involved.
Hi Sara,
I followed your steps and using own SID, AuthenticationCode and Verified number, but encounter the following:
14:32:59.773 -> connecting to api.twilio.com
14:32:59.773 -> Connecting to host api.twilio.com
14:32:59.773 -> Connection failed!
After 3 days were averything was working well sending SMS, now, i encounter the following:
14:32:59.773 -> connecting to api.twilio.com
14:32:59.773 -> Connecting to host api.twilio.com
14:32:59.773 -> Connection failed!
I’m having the same issue… Connection failed! Suddenly, all my ESP32 IOT devices have stopped connecting with Twilio. I’ve had stable Twilio connections for many months so this is very strange.
Hi.
Maybe it’s better to contact their support to see if they made any changes on the API or something.
Regards,
Sara
Hi Sara, Yes, Twilio changed their certificate on December 10th. As a result, the old certificate that was part of the twilio-esp32-client library no longer worked. Adam Demuri updated the library with a new certificate on December 3rd. So, once I compiled my code with this updated certificate, everything worked again. Yaay! Twilio warns against ‘pinning’ certificates in our microcontroller code and urges us to implement an automatic certificate update process, but that’s not something I know how to do. Consequently, I will have to see if my IOT devices are still working in December 2024 when Twilio updates their certificate.
Hi.
Thanks for sharing that info.
That’s something new to take a look at.
Regards,
Sara
Thanks for the heads up on the certificate update. I had to manually copy the digicert.cpp file into my IDE library file but it worked thanks again.
Could you provide updated code for this? I am still getting connection errors
d:\Documents\Arduino\libraries\twilio-esp32-client\src\twilio.cpp: In member function ‘bool Twilio::send_message(const String&, const String&, const String&, String&, const String&)’:
d:\Documents\Arduino\libraries\twilio-esp32-client\src\twilio.cpp:41:10: error: ‘class BearSSL::WiFiClientSecure’ has no member named ‘setCACert’
41 | client.setCACert(ca_crt);
| ^~~~~~~~~
d:\Documents\Arduino\libraries\twilio-esp32-client\src\twilio.cpp: In static member function ‘static String Twilio::_get_auth_header(const String&, const String&)’:
d:\Documents\Arduino\libraries\twilio-esp32-client\src\twilio.cpp:119:16: error: incomplete type ‘std::string’ {aka ‘std::__cxx11::basic_string’} used in nested name specifier
119 | std::string::size_type i = 0;
| ^~~~~~~~~
d:\Documents\Arduino\libraries\twilio-esp32-client\src\twilio.cpp:122:10: error: ‘i’ was not declared in this scope
122 | while (i < encoded_string.length()) {
| ^
this is the error i am currently facing…i downloaded the library from your github link, but still there is problem with library..kindly help me with it