In this guide, you’ll learn how to send messages to your WhatsApp account with the ESP32. This can be useful to receive notifications from the ESP32 with sensor readings, alert messages when a sensor reading is above or below a certain threshold, when motion is detected, and many other applications. We’ll program the ESP32 using Arduino IDE and to send the messages we’ll use a free API called CallMeBot.
We have a similar tutorial for the ESP8266 board:
Introducing WhatsApp
âWhatsApp Messenger, or simply WhatsApp, is an internationally available American freeware, cross-platform centralized instant messaging and voice-over-IP service owned by Meta Platforms.â It allows you to send messages using your phoneâs internet connection, so you can avoid SMS fees.
WhatsApp is free and is available for Android and iOS. Install WhatsApp on your smartphone if you donât have it already.
CallMeBot WhatsApp API
To send messages to your WhatsApp account with the ESP32, weâll use a free API service called CallMeBot service. You can learn more about CallMeBot at the following link:
Basically, it works as a gateway that allows you to send a message to yourself. This can be useful to send alert messages from the ESP32.
All the information about how to send messages using the API, can be found here.
Getting the CallMeBot API KEY
Before starting using the API, you need to get the CallmeBot WhatsApp API key. Follow the next instructions (check this link for the instructions on the official website).
- Add the phone number +34 621 331 709 to your Phone Contacts. (Name it as you wish) â please double-check the number on the CallMeBot website, because it sometimes changes.
- Send the following message: “I allow callmebot to send me messages” to the new Contact created (using WhatsApp of course);
- Wait until you receive the message “API Activated for your phone number. Your APIKEY is XXXXXX” from the bot.
Note: If you don’t receive the API key in 2 minutes, please try again after 24hs. The WhatsApp message from the bot will contain the API key needed to send messages using the API
CallMeBot API
To send a message using the CallMeBot API you need to make a POST request to the following URL (but using your information):
https://api.callmebot.com/whatsapp.php?phone=[phone_number]&text=[message]&apikey=[your_apikey]
- [phone_number]: phone number associated with your WhatsApp account in international format;
- [message]: the message to be sent, should be URL encoded.
- [your_apikey]: the API key you received during the activation process in the previous section.
For the official documentation, you can check the following link: https://www.callmebot.com/blog/free-api-whatsapp-messages/
Installing the URLEncode Library
As we’ve seen previously, the message to be sent needs to be URL encoded. URL encoding converts characters into a format that can be transmitted over the Internet. URLs can only be sent over the Internet using the ASCII character-set.
This will allow us to include characters like ç, ÂȘ, Âș, Ă , ĂŒ in our messages. You can learn more about URL encoding here.
You can encode the message yourself, or you can use a library, which is much simpler. We’ll use the UrlEncode library that can be installed on your Arduino IDE.
Go to Sketch > Include Library > Manage Libraries and search for URLEncode library by Masayuki Sugahara as shown below.
Sending Messages to WhatsApp – ESP32 Code
The following example code sends a message to your WhatsApp account when the ESP32 first boots. This is a simple example to show you how to send messages. After understanding how it works, the idea is to incorporate it into your own projects.
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-send-messages-whatsapp/
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.
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <UrlEncode.h>
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// +international_country_code + phone number
// Portugal +351, example: +351912345678
String phoneNumber = "REPLACE_WITH_YOUR_PHONE_NUMBER";
String apiKey = "REPLACE_WITH_API_KEY";
void sendMessage(String message){
// Data to send with HTTP POST
String url = "https://api.callmebot.com/whatsapp.php?phone=" + phoneNumber + "&apikey=" + apiKey + "&text=" + urlEncode(message);
HTTPClient http;
http.begin(url);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Send HTTP POST request
int httpResponseCode = http.POST(url);
if (httpResponseCode == 200){
Serial.print("Message sent successfully");
}
else{
Serial.println("Error sending the message");
Serial.print("HTTP response code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
// Send Message to WhatsAPP
sendMessage("Hello from ESP32!");
}
void loop() {
}
How the Code Works
Sending a message to WhatsApp using the CallMeBot API is very straightforward. You just need to make an HTTP POST request.
First, include the necessary libraries:
#include <WiFi.h>
#include <HTTPClient.h>
#include <UrlEncode.h>
Insert your network credentials on the following variables:
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Insert your phone number and API key. The phone number should be in international format (including the + sign).
String phoneNumber = "REPLACE_WITH_YOUR_PHONE_NUMBER";
String apiKey = "REPLACE_WITH_YOUR_API_KEY";
sendMessage()
We create a function called sendMessage() that you can call later to send messages to WhatsApp. This function accepts as an argument the message you want to send.
void sendMessage(String message){
Inside the function, we prepare the URL for the request with your information, phone number, API key, and message.
As we’ve seen previously, the message needs to be URL encoded. We’ve included the UrlEncode library to do that. It contains a function called urlEncode() that encodes whatever message we pass as argument (urlEncode(message)).
String url = "https://api.callmebot.com/whatsapp.php?phone=" + phoneNumber + "&apikey=" + apiKey + "&text=" + urlEncode(message);
Create and start an HTTPClient on that URL:
HTTPClient http;
http.begin(url);
Specify the content type:
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
Finally, send the HTTP post request. The following line sends the request and saves the response code:
int httpResponseCode = http.POST(url);
If the response code is 200, it means the post request was successful. Otherwise, something went wrong.
// Send HTTP POST request
int httpResponseCode = http.POST(url);
if (httpResponseCode == 200){
Serial.print("Message sent successfully");
}
else{
Serial.println("Error sending the message");
Serial.print("HTTP response code: ");
Serial.println(httpResponseCode);
}
Finally, free up the resources:
// Free resources
http.end();
setup()
In the setup(), initialize the Serial Monitor for debugging purposes.
Serial.begin(115200);
Connect to your local network and print the board IP address.
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Then, we can send a message to WhatsApp by simply calling the sendMessage() function. In this case, we’re sending the message Hello from ESP32!
// Send Message to WhatsAPP
sendMessage("Hello from ESP32!");
Demonstration
After inserting your network credentials, phone number and API key, you can upload the code to your board.
After uploading, open the Serial Monitor at a baud rate of 115200 and press the board RST button. It should successfully connect to your network and send the message to WhatsApp.
Go to your WhatsApp account. After a few seconds, you should receive the ESP32 message.
Wrapping Up
In this tutorial, you learned how to use the CallMeBot API with the ESP32 to send messages to your WhatsApp account. This can be useful to send sensor readings regularly to your inbox, send a notification when motion is detected, send an alert message when a sensor reading is above or below a certain threshold, and many other applications.
We also have tutorials for other types of messages (email and Telegram messages):
- ESP32 Send Emails using an SMTP Server: HTML, Text, and Attachments (Arduino IDE)
- Telegram: Control ESP32/ESP8266 Outputs (Arduino IDE)
- Telegram: Request ESP32/ESP8266 Sensor Readings (Arduino IDE)
- ESP32 Door Status Monitor with Telegram Notifications
We hope you find this tutorial useful.
Learn more about the ESP32 with our resources:
- Learn ESP32 with Arduino IDE
- Build Web Servers with ESP32 and ESP8266
- Firebase Web App with ESP32 and ESP8266
- Free ESP32 Projects and Tutorials
Thanks for reading.
Would be possible to use a ESP8266 instead? I have multiple of those laying around the house and it would be a good project to try. Would you say an ESP32 is a more flexible platform than the 8266? I am very familiar with the later but never used the esp32.
Hi.
We’ll publish a similar tutorial for the ESP8266 tomorrow. So, stay tuned!
Regards,
Sara
Thanks for the heads up, your content is always top notch!
Thank you Sara for your wonderful tutorials.
It is so helpfull!
Regards.
Peter Lörne
Great!
I’m glad this is helpful.
Regards,
Sara
Is there a Callmebot tutorial using ESP8266?
Hi.
Yes.
Here it is: https://randomnerdtutorials.com/esp8266-nodemcu-send-messages-whatsapp/
Regards.
Hello
Again, a wonderful tutorial.
I use Callmebot with iobroker to tell me when the washing machine is ready.
But I found out that Callmebot is not free.
I’m still happy to pay the 40ct per month and support the maker to provide us with such a platform. To try it out you can use it for free, after a few days you will get a request from Callmebot asking for support.
Greetings Infoschwab
Great project as always. Thanks.
Thanks đ
Very useful, thanks.
upython users can use urequests directely with the HTTP adress.
Exactly what I needed. Thanks. Slight error in code, constant character declarations need semi colons. OK in code explanation, but raw code and initial presentation, semi colons are missing.
Hi.
You’re right. It was a typo when pasting the code to GitHub.
It’s fixed now. Thanks.
Regards,
Sara
Great project as usually Sara.
We are waiting for a simple example on how to manage an alert messages when a sensor reading is above or below a certain threshold.
Thanks.
Thanks.
We’ll work on it.
Regards,
Sara
Excellent tutorial as always, thank for that.
My concern is about privacy, providing that your message is being sent to a third party site that forwards it to you. With the information that you load in the site, can’t this third party send other undesired messages to you? I’m not saying that they’re going to do, but if they’re hacked…. Telegram APIs don’t need a third party site, I think.
Having problems finding the right library for #include <HTTPClient.h>
I found #include <HttpClient.h> from HttpClient-2.2.0.zip, but camel-case is very different from what you used. Could you send me a link to the right one?
Hi.
You don’t need to install any library.
It’s the default library that comes with the ESP32-arduino package.
Regards,
Sara
got same problem – you have to update to a newer esp32 package (currently using V2.0.5) in boardmanager, so now this is working properly!
https://github.com/espressif/arduino-esp32
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json
Thank you for bringing this to our attention! I’m not sure if this will remain a possibility for long, but for now I’ll make use of it! thanks again. Regards.
hello,
thanks for demo.. i can now send text .. but how to send a VARIABLE ? .. like my sensor reading is 23.7 next minute it is 23.9 or so .. so how to send variables instead of “message”
that variable temperature is stored in int. named Ctemp so if i sent “Ctemp” it is sent as a text named Ctemp not its integer value… can you help please?
– just what would be the syntax for that?
Send it as:
sendMessage(String(Ctemp));
Hola Sara, si puedo enviar el dato del sensor, pero como puedo enviar por ejemplo, Temperatura= (dato), osea el texto y el dato juntos, porque puedo enviar o uno u otro, pero para incluir varios mensajes juntos?, saludos y gracias
Thanks for the excellent tutorials, all very helpful.
I’m usina ESP32 board and Arduino IDE. I followed the steps on the tutorial but when I run the sketch always receive this message on serialmonitor: “Error sentindo the message. HTTP responde code: 403. Do you know how to fix it? Thanks a lot.
Hi, I just found out my mistake.
I included the urlEncode function incidente the quotation marks, like this:
String url = “https://api.callmebot.com/whatsapp.php?phone=1234567890″&apikey=1234567&text=urlEncode(message)”;
And the correct was:
https://api.callmebot.com/whatsapp.php?phone=1234567890“&apikey=1234567&text=”urlEncode(message);
Problem SOLVED.
Thanks!
Serait ce possible Ă la place d’utiliser micropython avec ce projet d’envoie de message whatsapp
Hi !!!! greetings from Argentina. Done the project with ESP32 , sound sensor and pir sensor, works incredibly !!
I read a comment from a user that in few days callmebot stops being free, is it true ?
Is it possible to use both ways, I mean, receive a message from an event, and send a whatsapp message to ESP32 so it turns HIGH or LOW a given port.
Thanks for everything !!!!!!!!!!
callmebot is a free API for personal use: https://www.callmebot.com/blog/free-api-whatsapp-messages/
Hi Rodolfo, greetings from Brazil.
In fact, Callmebot stopped to being free in a few days and I had to pay to continue using it.
Hi Sara, you guys rock
How do esp send WhatsApp message to my phone? Do it need internet connection to send it with?
Hi.
Yes, you need internet connection so that ESP32 can connect with the callmebot API that will take care of sending the message.
Regards,
Sara
Hallo, super Beitrag wie immer – auf Ihre BeitrĂ€ge kann man sich verlassen, vor allen Dingen wenn man nicht ganz so firm ist mit der Programmierung.
Nun zu meiner Frage: Haben Sie schon eine Variante um z.B. das Signal eines Bewegungsmelders an WhatsApp zu senden ?
Unbedingt veröffentlichen wenn es soweit ist…..
Vielen Dank
XXAL
This is amazing tutorial. I’m hoping to get back to this hobby asap.
Thanks for the awesome tutorial!
I am however getting the http response code 203 – Non-Authoritative Information.
Does anyone know how I could resolve this issue.
Thanks:)
Sara:
My sckech indicated error 400, can you help me please.
Thanks
Hi.
Did you modify the code with all the required details?
Regards,
Sara
Hi,
This is a great tutorial, thanks !
I have been using it with succes in a project with a dynamic IP address.
However, when I switch over to a static IP address, the CallMeBot app isn’t working anymore.
Here is the static IP address that I declared (Arduino / ESP32) :
IPAddress local_IP(192, 168, 1, 184);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);
Do you have any idea why the app is not working with a static IP address ?
The rest of my application (including WiFi and BT), is working fine, except CallMeBot…)
Thanks in advance for your feedback.
Kind regards
Guy
hi! im having http response code 203. what can be the reason? Have anyone had the same problem before? Thanks in advance!
Are you using a proxy?
Hi Sara,
this is a great project. I tried it out and works like magic.
but i want to know how the esp32 can get a message sent from same whatsapp.
Also, i want the esp32 to send message to a whatsapp group. i hope that is possible too. please assist me.
Hi.
Unfortunately, at the moment, we don’t have any tutorials covering that subject.
Regards,
Sara
I also tried your esp32cam telegram photo projects, i works perfectly, can you help replicated on whatsapp?
Neither number works in USA for CallMe Bot have tried several times to get API key but no reply. Tried changing to USA country code of +1 doesn’t work eother.
Hi.
Please contact their support team to try to fix the issue: https://www.callmebot.com/#need_support
Regards,
Sara
Dear Sara, first of all, congratulations to you and Rui for the tutorials that make our life as an engineer easier…
I tried to connect with CallMeBot using the number +34 644 31 95 65 without success, even after 24h, so looking at https://www.callmebot.com/blog/free-api-whatsapp-messages/ I saw that they inform the number +34 644 51 95 23.
After changing it, I received the API key successfully.
I think is interesting to update this number in the post. Hugs!
Hi.
It seems they changed the number.
I’ll update the tutorial.
Thanks for pointing that out.
Regards,
Sara
I’m developing a leak detector for my home, for personal use. CallMeBot started adding messages asking for money this morning April 3, 2023. It is now counting down the number of messages I have left…
I checked on the website, and there is no mention of money or payment anywhere.
Beware. It’s not really Free for personal use.
Maybe I exceeded a certain number of messages while developing, but free should be free. If it stated a limit for free, that would be understandable, but there is nothing on the website. Ultimately I just needed one weekly message with battery status, but right now I’m testing the code. I guess I’ll just stick with email. (Thanks for your tutorial on that!).
Hi.
I never had issues using callmebot. They never asked me for any money.
Send them an email to their support asking about your situation.
Regards,
Sara
Hello,
I contacted callmebot, and they replied that they are starting to charge for people who use their service a lot, even for personal use. I pointed out that they do not mention this on their website, nor do they mention what “a lot” is.
While developing my personal water leak alarm, I guess I passed a threshold. If I was aware of the threshold, I would have tried to stay under it. Callmebot hasn’t replied when I asked about the threshold, and so far they still claim to be free for personal use…obviously they are not.
Hi
Is there a possibility to get instead a Whatsapp or E Mail notification an alarm tone on the mobile phone?
Is this possible via IFTTT or other service?
Tks for sending some idea
BR
Joe
Thank you Sarah for this wonderful tuto and for all off them.
I used this and many of your tutorials to monitor temperatures of my gas and solar central heating system. As it is 12 years old, it was not connected to internet. The ESP systems read tDS18B20 temperature on different water pipe, BH11 humidity and displays them on oled screen, records them every 5 min on a SD card, display them, totalized, average them on a HTML web page and send WhatsApp messages every day to send temperature or in case of sensors errors. Itâs connected to a real time clock.
I also had to pay Callmebot, 4 euro par year, itâs OK.
I still have several ideas to improve this project, but some days I may reach the ESP32 memory limits.
Regards
Jean-Yves
Seems a great project.
Thanks for sharing those details.
Regards,
Sara
I think they made a change to the API
the tutorial address is
String url = “http://api.callmebot.com/whatsapp.php?phone=yyyy&apikey=XXXX&text=message”;
but in the message I received as an example it is different
String url = “https://api.whatabot.net/whatsapp/sendMessage?apikey=XXXX&text=message&phone=yyyy”;
the address is different “.com” >>> “.net”
It’s a PHP script
It’s on HTTPS
and the different order
Hi, how can I send the message to more than one numbers at once? or maybe to a whatsapp group?
Hi.
Yes, we have a tutorial about that: https://randomnerdtutorials.com/telegram-group-esp32-esp8266/
Regards,
Sara
Hello Sara i’m having troubles with send the message it shows me on the console :
…
Connected to WiFi network with IP Address: 192.168.1.21
Error sending the message
HTTP response code: 203
I really aprecciate if you would you kindly to help me
Howya,
Check your phone number. I had same error code
Error sending the message
HTTP response code: 203
Then I noticed that I have an extra number( fat fingers on keypad đ
Also I tried my missus phone number to send her “hearts” đ from ESP32
Same error code. Must be related to phone number, I guess.
Good luck
Stef
Best regards to all friends who contributed and contributed. I want to learn: With Esp32, can esp32 Bluetooth coverage area send messages to all mobile phones? Mobile users will not give their mobile numbers. Example: Can information messages be sent to the WhatsApp accounts of the participants in an event? Thank you in advance for your interest. .
Hi,
I’m trying to use the example code on Uno R4 WiFi board but got ” Compilation error: HTTPClient.h: No such file or directory”.
I already installed to latest version of this board (2.0.18) and esp board (3.0.7)
Please help! I’m stuck.