ESP8266 NodeMCU: Send Messages to WhatsApp

In this guide, you’ll learn how to send messages to your WhatsApp account with the ESP8266 NodeMCU board. This can be useful to receive notifications from the ESP8266 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 ESP8266 using Arduino IDE and to send the messages we’ll use a free API called CallMeBot.

ESP8266 NodeMCU Send Messages to WhatsApp Arduino IDE

We have a similar tutorial for the ESP32 board:

Introducing WhatsApp

WhatsApp logo

“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 ESP8266, 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 ESP8266.

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).

  1. 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.
  2. Send the following message: “I allow callmebot to send me messages” to the new Contact created (using WhatsApp of course);
  3. Wait until you receive the message “API Activated for your phone number. Your APIKEY is XXXXXX” from the bot.
Get CallMeBot API key

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.

Install URL Encode Library Arduino IDE

Sending Messages to WhatsApp – ESP8266 Code

The following example code sends a message to your WhatsApp account when the ESP8266 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/esp8266-nodemcu-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 <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.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 = "http://api.callmebot.com/whatsapp.php?phone=" + phoneNumber + "&apikey=" + apiKey + "&text=" + urlEncode(message);
  WiFiClient client;    
  HTTPClient http;
  http.begin(client, 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 ESP8266!");
}

void loop() {
  
}

View raw code

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 <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.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 = "http://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 ESP8266!

// Send Message to WhatsAPP
sendMessage("Hello from ESP8266!");

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.

ESP8266 Send Message to WhatsApp Serial Monitor

Go to your WhatsApp account. After a few seconds, you should receive the ESP8266 message.

WhatsApp Receive Message from ESP8266

Wrapping Up

In this tutorial, you learned how to use the CallMeBot API with the ESP8266 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 more applications.

We also have tutorials for other types of messages (email and Telegram messages):

We hope you find this tutorial useful.

Learn more about the ESP8266 with our resources:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

42 thoughts on “ESP8266 NodeMCU: Send Messages to WhatsApp”

  1. Hi,
    I saw your 2 articles on sending data to WhatsApp and sending a trigger from Telegram to an ESP device. But is there a way of doing both? In other words requesting a sensor reading by sending a command from your phone.
    Thanks,
    Mike

    Reply
  2. Hello miss sara, i am getting help in my every project by your links and toturials. Is there any code that we can send image or picture from esp32 cam to esp 32 via Ble/wifi such as client to server ?

    Reply
  3. there is a little mistake in this line. my code work in this way. here i mentioned the updated line. kindly check and update the code for new user.
    String url = “http://api.callmebot.com/whatsapp.php?phone=” + phoneNumber + “&apikey=” + apiKey + “&text=” + urlEncode(“message”);

    Reply
  4. Callmebot is quite versatile. Works with Whatsapp, Signal, telegram and Facebook messenger.
    Telegram also has its own interface that can be used without callmebot

    Reply
  5. Hi!
    Tried getting a API Key. Was unsuccessful 4 times. Has anybody faced this issue. Does it work across the globe? I am from India.

    Reply
  6. Hello, thank you for the tutorial very well explained.
    A question, how to integrate a value in the message?
    I would like to send an alarm message when the temperature of the freezer is less than -15 C. The measured value is called “TempCongelo”.
    Is this solution correct?
    sendMessage(“FREEZER ALARM ,” (TempCongelo) “°C”)
    Thank you for answer, Regards, Stéphane

    Reply
  7. Good evening, an additional problem, impossible to send a message, error ad: Error sending the message HTTP response code: -1.
    My sketch encompasses the sending of data to influxDB, on the basis of the tutorial “ESP32/ESP8266: Send BME280 Sensor Readings to InfluxDB”
    Is it possible that the resources are occupied by sending to InfluxDB? If so, how can I free the resources?
    Thanks

    Reply
    • Hello, well, no help.
      If this can be useful for someone, I have solved my problems using InfluxDB to alarm (alert section). Simply a PHP file under /var/www/html/alertmessage/alertmessage.php. File content:
      $phone=’+49123123123′;
      $apikey=’123456′;
      $message=’This is a test from PHP’;

      $url=’https://api.callmebot.com/whatsapp.php?source=php&phone=’.$phone.’&text=’.urlencode($message).’&apikey=’.$apikey;
      $html=file_get_contents($url);
      source: https://www.callmebot.com/blog/whatsapp-from-php/
      “Endpoints” calls this file when the conditions are “true”
      I am now working to transfer a suitable message ($ message), in the “Rules notification” section. But I don’t know PHP. This principle is very flexible and the changes are possible without reprogramming the ESP8266.

      Reply
    • Hi.
      It seems they changed their number.
      I updated the tutorial just now.
      This is the new number
      +34 644 44 21 48
      Regards,
      Sara

      Reply
  8. C:\Users\UNKNOWN\Desktop\WHATSAPP_MESSAGES\WHATSAPP_MESSAGES.ino:4:10: fatal error: UrlEncode.h: No such file or directory
    4 | #include <UrlEncode.h>
    | ^~~~~~~~~~~~~
    compilation terminated.

    exit status 1

    Compilation error: UrlEncode.h: No such file or directory

    Reply
    • Hi.
      As it is mentioned in the error, it can’t find that library.
      It means you need to install the UrlEncode library as mentioned in the tutorial.
      Please follow all the described steps to make it work.
      Regards,
      Sara

      Reply
  9. Hello, if I copy your code to my ESP8266 and connect I get the following result:
    ……..
    Connected to WiFi network with IP Address: 192.168.2.213
    Error sending the message
    HTTP response code: 203

    What can I do?

    Reply
  10. Greetings.
    I have the following difficulty.
    I installed URLEncode library but still I get following
    error message when I try to compile
    LAST LINE OF ERROR MESSAGE is as follows

    c:\users\admin\appdata\local\arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\3.1.0-gcc10.3-e5f9fec\xtensa-lx106-elf\include\c++\10.3.0\bits/std_function.h:610: undefined reference to `Z30schedule_recurrent_function_usRKSt8functionIFbvEEjS3
    collect2.exe: error: ld returned 1 exit status

    exit status 1

    Compilation error: exit status 1

    Please guide me why this “Undefined Reference” Error comes & how to solve it.

    Reply
  11. Greetings !
    I am continuing from my previous message.
    Above mentioned error came when I tried to compile using my laptop but
    when I tried to compile using desktop, it was a successful compilation.
    A test message was also received successfully.
    I think there maybe some issue with Arduino IDE installation or OS of my laptop.
    I don’t know exactly. I need to check.
    If someone knows the reason behind this, please let me know.

    Reply
    • Hi.
      I’m not familiar with that error. But it seems an issue with your Arduino IDE installation.
      I would remove all Arduino IDE folders and reinstall it again.
      Regards,
      Sara

      Reply
      • Thanks Sara Madam.
        I will re install Arduino IDE in my laptop as you say.

        Another point is, on 23rd August, the program was compiled ok on desktop but it is not getting compiled since 24th August onwards.
        The following error is coming :

        C:\Users\mentor\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2/tools/sdk/include/bearssl/bearssl_rsa.h:3:150: error: extended character ⦫ is not valid in an identifier

        Shall I reinstall Arduino IDE on my desktop also ?
        Or, is there any other reason ?

        Reply
  12. Thankyou for this tutorial, I made this for myself & it’s working awesome.
    By the way is there any limit of number of messages per day or per hour of the api?

    Reply
  13. Cuando fijo Ip local en el ESP8266 con:

    IPAddress ip(192,168,1,101);
    IPAddress gateway(192,168,1,1);
    IPAddress subnet(255,255,255,0);

    no es posible enviar el mensaje

    Error sending the message
    HTTP response code: -1

    cual será la solución?
    Gracias

    Reply
  14. Hi Sara.
    I have the following difficulty.

    c:\Users\ASUS\Documents\Arduino\libraries\ESP8266wifi\src\lwip\src\apps\httpd\fs.c:33:10: fatal error: lwip/apps/httpd_opts.h: No such file or directory
    33 | #include “lwip/apps/httpd_opts.h”
    | ^~~~~~~~~~~~~~~~~~~~~~~~
    compilation terminated.
    Multiple libraries were found for “ESP8266WiFi.h”
    Used: C:\Users\ASUS\Documents\Arduino\libraries\ESP8266wifi
    Not used: C:\Users\ASUS\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\ESP8266WiFi
    exit status 1

    Compilation error: exit status 1

    Reply
  15. Hola Sara Santos.
    Mi nombre es Javier de España
    Le escribo en castellano, no creo tenga problema.
    Mi pregunta he probado el esp8266-nodemcu-send-messages-whatsapp/
    ESP8266 NodeMCU: Send Messages to WhatsApp
    y funciona muy bien, y me llega los whatsapp bien. yo queria utilizar este codigo como el de ESP8266 NodeMCU Door Status Monitor with Telegram Notifications, pero para whatsapp, o sea cuando abra la puerta un mensaje de puesta abierta y cuando se cierre , puerta cerrada. Creo que serian pocas modificaciones. Ya me dice, muchas gracias por sus fantasticos proyectos y la pagina es un 100 , FELECIDADES.
    Hello Sara Santos.
    My name is Javier from Spain
    I write to you in Spanish, I don’t think you have a problem.
    My question I have tried esp8266-nodemcu-send-messages-whatsapp/
    ESP8266 NodeMCU: Send Messages to WhatsApp
    and it works very well, and I receive WhatsApp well. I wanted to use this code like that of ESP8266 NodeMCU Door Status Monitor with Telegram Notifications, but for WhatsApp, that is, when I open the door, a message shows it open and when it closes, the door is closed. I think there would be few modifications. You already tell me, thank you very much for your fantastic projects and the page is a 100, CONGRATULATIONS.
    ​

    Reply
  16. Hi!
    Follow your Blog. Some Articles are very helpfull and finished.
    Also read the Article about ESP8266 sending WhatsApp.
    Nice Intro, but in this case senceless.
    Sorry, but this kind of Tutorial has no learningcurve, whatfor should it be?
    Better to take an real example like you post at the End (send an alert message when a sensor reading is above or below a certain threshold).
    This would be realy usefull!

    Best Regards

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.