📧 Sending email and SMS with NodeMCU ESP8266


Since its launch in 2014, the ESP8266 microcircuit has introduced fundamental changes in the field of the Internet of Things, providing professionals and enthusiasts with an extremely economical programmable microcontroller with an integrated WiFi module, thereby opening up access to the Internet for all sorts of everyday things and sensors.

In addition, thanks to the Wi-Fi module, the ESP8266 can also serve as a stand-alone web server on the local network and respond to requests as an HTTP GET method received from an Internet browser. This project shows how to build a simple stand-alone weather web server using the NodeMCU ESP8266 and the BME280 environmental sensor from Bosch.

Upon receiving a web request, NodeMCU sends back an HTML web page containing temperature and humidity and atmospheric pressure. With an HTML update tag, the page automatically reloads every 15 seconds to get the latest environmental data.

To master the basic idea, we need only the NodeMCU ESP8266 board and the power supply. Usually, power is supplied by a USB cable. We will not need either sensors or any other means – to demonstrate the method we will simply generate random numbers at certain intervals, and in cases where the number exceeds the specified limit value, we will expect a letter and/or text message.

As in the case of sending data from the ESP8266 chip to Google Tables, we will create a new Table on the Google Disk.

Let’s do the following:

1. Open your Google Drive in a web browser and create a new Google Spreadsheet. You can name this file as you like. I called it “SendEmailAndText_ESP8266”.

2. In the newly created Google Tables window, select the menu item “Tools> Script editor”.

3. Using the toolbar, set the name of the main script editor file (any, as you like).

4. Paste the following code into the Code.gs file or “Code.gs” (assuming that you did not change the default file name). Again, the name of this file has no meaning, but the code below specifies “SendEmailAndText_ESP8266”.

// 0) From Google spreadsheet, Tools > Script Editor…
// 1) Write your code
// 2) Save and give a meaningful name
// 3) Run and make sure “doGet” is selected
//    You can set a method from Run menu
// 4) When you run for the first time, it will ask
//    for the permission. You must allow it.
//    Make sure everything is working as it should.
// 5) From Publish menu > Deploy as Web App…
//    Select a new version every time it’s published
//    Type comments next to the version
//    Execute as: “Me (your email address)”
//    MUST: Select “Anyone, even anonymous” on “Who has access to this script”
//    For the first time it will give you some prompt, accept it.
//    You will need the given information (url) later. This doesn’t change, ever!
var number = “8001239999”; // your phone number
var domain = “tmomail.net”; // You may find your domain for you carrier at: http://www.emailtextmessages.com/
var toEmail = [email protected];
function doGet(e){
  Logger.log(“— doGet —“);
  // for debugging
  if (e == null){e={}; e.parameters = {value:“-1”};}
    // get the values from parameters to local var
    var value = e.parameters.value;
    var phoneEmail = number + “@” + domain;
    // Send Text Message (SMS)
    send_Email(phoneEmail, “NodeMCU here, your sensor went beyond your threshold. Sensor reported: “ + value + ” on:” + new Date());
    // Send Email
    var message = Dear User,
Your equipment has reached it’s threshold value. It just reported a value of “ + value + “. Please take a necessary action.
    message += “As a valued customer, we have sent you a text message also.
    message += “To learn more about this email, please click on the link below:
    message += “<a href="http://www.embedded-lab.com/” target=”new”>www.Embedded-Lab.com
    message += “Sincerely,
<b>NodeMCU ESP8266</b>“;
    send_Email(toEmail, message)
    return ContentService.createTextOutput(“Things went successfully.“);
   catch(error) {
    return ContentService.createTextOutput(“oops....” + error.message
                                            + “n” + new Date()
                                            + “nnumber: ” + number +
                                            + “ndomain: ” + domain);
function send_Email(address, message){
          “to“: address,
     “subject“: “Threshold reached ESP8266“,
    “htmlBody“: message      
  Logger.log(“send_textMessage: ” + “Email sent to: + address);

As shown in the figure below, click the “doGet” area and then click the button with a bug to begin debugging the code. If you completed the steps correctly, then you should receive a text message and an email from your Gmail account.

Please note that Google will need permission to send an email on your behalf, so when Google asks for permission and you will need to confirm it.


 If you have not received a text message and/or email, then double-check the steps again. If everything worked out, then publish this script to get a URL with which we can work through the NodeMCU board.

To publish, select the “Publish> Deploy as Web App” menu item.


 Before you start building, you should see a window with settings. Be sure to configure all three options, as shown in the figure below.

 After clicking Update (“Update”) or Publish (“Expand”) you will see the following window. Copy the address from this window. We recommend saving this address in the script itself, for ease of future use. In the future, we will need this address for writing software for the NodeMCU ESP8266.

Note: we will call the text between the characters “/ s /” and “/ exec” as GScriptID. This information will be needed for the NodeMCU board code.

Take the URL from the window shown above and add it? Value = -1 to it.

The address will look something like this:


Now paste this address in the address field of the browser and press Enter. After a few seconds, you should receive an email and a text message.

Be sure to install a library that will help us process the request redirection (redirection).

#include “ESP8266WiFi.h”
#include “HTTPSRedirect.h”

const char* ssid = “–Your SSID–“;
const char* password = “–Your Password–“;

// The ID below comes from URL
// after publishing Google Script as Web App.
const char *GScriptId = “–Your GScriptId–“;

const char* host = “script.google.com”;
const char* googleRedirHost = “script.googleusercontent.com”;

const int httpsPort = 443;
HTTPSRedirect client(httpsPort);

// Prepare the url (without the varying data)
String url = String(“/macros/s/”) + GScriptId + “/exec?”;

const char* fingerprint = “F0 5C 74 77 3F 6B 25 D7 3B 66 4D 43 2F 7E BC 5B E9 28 86 AD”;

void setup() {
Serial.println(“Connecting to wifi: “);

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.println(” IP address: “);
Serial.print(String(“Connecting to “));

bool flag = false;
for (int i=0; i<5; i++){
int retval = client.connect(host, httpsPort);
if (retval == 1) {
flag = true;
Serial.println(“Connection failed. Retrying…”);

// Connection Status, 1 = Connected, 0 is not.
Serial.println(“Connection Status: “ + String(client.connected()));

if (!flag){
Serial.print(“Could not connect to server: “);

// Data will still be pushed even certification don’t match.
if (client.verify(fingerprint, host)) {
Serial.println(“Certificate match.”);
} else {
Serial.println(“Certificate mis-match”);

// This is the main method where data gets pushed to the Google sheet
void sendValueToGoogle(String value){
if (!client.connected()){
Serial.println(“Connecting to client again…”);
client.connect(host, httpsPort);
String urlFinal = url + “value=” + value;
client.printRedir(urlFinal, host, googleRedirHost);

// Continue pushing data at a given interval
void loop() {

// Here you will have your main code
// To demonstrate the concept we are generating a random number
long randomValue = random(10, 20);

// Our lower threshold is 12 and upper threshold is 18
// when given vlaue goes below lower or above upper the threshold
// we would like to send information to GAS for email and text message
if (randomValue 18) {
Serial.println(“Random value outside the threshold: “ + String(randomValue));

delay (10000); // wait 10 sec

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest