ESP32/ESP8266 Send Email Notification using PHP Script

In this project you’ll build an ESP32 or ESP8266 client that makes an HTTP POST request to a PHP script to send an email notification with sensor readings.

ESP32 ESP8266 Send Email Notification using PHP Script

You can also set a threshold value, so your email notification is only sent if the temperature/humidity/pressure is above a certain value.

As an example, we’ll be using a BME280 sensor connected to an ESP32 or ESP8266 board. You can modify the code provided to send readings from a different sensor or even use multiple boards.

This is a great way to send email notifications using the ESP32 or ESP8266 without relying on IFTTT or an SMTP server.

In order to build this project, you will:

  • Host a server and setup a domain name
  • Create PHP script to send email notifications
  • Program ESP32 or ESP8266 with Arduino IDE

This project is also a great addition to built upon our previous projects:

1. Hosting Your PHP Application

The goal of this project is to have your own domain name and hosting account that allows you send email notifications (without using an SMTP server, IFTTT, etc…).

Here’s a high level overview on how the project works:

Hosting PHP Application to send email of ESP32 or ESP8266 BME280 Sensor Readings

I recommend using one of the following hosting services that can handle all the project requirements:

  • Bluehost (user-friendly with cPanel): free domain name when you sign up for the 3-year plan. I recommend choosing the unlimited websites option;
  • Digital Ocean: Linux server that you manage through a command line. I only recommended this option for advanced users.

Those two services are the ones that I use and personally recommend, but you can use any other hosting service. Any hosting service that offers PHP and MySQL will work with this tutorial. If you don’t have a hosting account, I recommend signing up for Bluehost.

Get Hosting and Domain Name with Bluehost »

When buying a hosting account, you’ll also have to purchase a domain name. If you like our projects, you might consider signing up to one of the recommended hosting services, because you’ll be supporting our work.

Note: you can also run a LAMP (Linux, Apache, MySQL, PHP) server on a Raspberry Pi, but it can’t send emails standalone. To send an email with a Raspberry Pi using PHP, you need to use an SMTP (Simple Mail Transfer Protocol) server.

2. PHP Script HTTP – Send Email Notification

After signing up for a hosting account and setting up a domain name, you can login to your cPanel or similar dashboard.

After that, follow the next steps to create a PHP script that is responsible for receiving incoming requests from the ESP32/ESP8266 and sending an email.

If you’re using a hosting provider with cPanel, go to Advanced and search for “File Manager“:

ESP32 ESP8266 CPanel Open Create Edit PHP Files

Then, select the public_html option and press the “+ File” button to create a new .php file.

ESP32 ESP8266 CPanel Create New PHP File

Note: if you’re following this tutorial and you’re not familiar with PHP, I recommend creating that exact file. Otherwise, you’ll need to modify the ESP sketch provided with a different URL path.

Create a new file in /public_html with this exact name and extension: email-notification.php

PHP Create New file email notification

Edit the newly created file (email-notification.php) and copy the following script:

<?php

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-send-email-notification/
  
  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.
*/

// Receiver Email Address (where to send email notification)
$email_address = "YourEmailAddress@example.com";

// Keep this API Key value to be compatible with the ESP code provided in the project page. If you change this value, the ESP sketch needs to match
$api_key_value = "tPmAT5Ab3j7F9";

$api_key = $value1 = $value2 = $value3 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $api_key = test_input($_POST["api_key"]);
    if($api_key == $api_key_value) {
        $value1 = test_input($_POST["value1"]);
        $value2 = test_input($_POST["value2"]);
        $value3 = test_input($_POST["value3"]);
        
        // Email message
        $email_msg = "Temperature: " . $value1 . "ºC\nHumidity: " . $value2 . "%\nPressure: " . $value3 . "hPa";
        
        // Use wordwrap() if lines are longer than 70 characters
        $email_msg = wordwrap($email_msg, 70);
        
        // Uncomment the next if statement to set a threshold 
        // ($value1 = temperature, $value2 = humidity, $value3 = pressure)
        /*if($value1 < 24.0){
            echo "Temperature below threshold, don't send email";
            exit;
        }*/
        
        // send email with mail(receiver email address, email subject, email message)
        mail($email_address, "[NEW] ESP BME280 Readings", $email_msg);
        
        echo "Email sent";
    }
    else {
        echo "Wrong API Key provided.";
    }

}
else {
    echo "No data posted with HTTP POST.";
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

View raw code

Before saving the file, you need to modify the $email_address variable with the receiver email address:

// Receiver Email Address (where to send email notification)
$email_address = "YourEmailAddress@example.com";

After adding the receiver email, save the file and continue with this tutorial. If you try to access your domain name in the next URL path, you’ll see the following:

http://example.com/email-notification.php
ESP32 ESP8266 Test Email Notification PHP URL

If you see that message, it means that everything is being setup properly. You can continue with this project.

3. Preparing Your ESP32 or ESP8266

This project is compatible with both the ESP32 and ESP8266 boards. You just need to assemble a simple circuit and upload the sketch provided to publish temperature, humidity, and pressure readings to your PHP script, that will then be responsible to handle email notifications.

Parts Required

For this example we’ll get sensor readings from the BME280 sensor. Here’s a list of parts you need to build the circuit for this project:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematics

The BME280 sensor module we’re using communicates via I2C communication protocol, so you need to connect it to the ESP32 or ESP8266 I2C pins.

BME280 wiring to ESP32

BME280ESP32
SCK (SCL Pin) GPIO 22
SDI (SDA pin) GPIO 21

So, assemble your circuit as shown in the next schematic diagram (read complete Guide for ESP32 with BME280).

BME280 wiring to ESP32

Recommended reading: ESP32 Pinout Reference Guide

BME280 wiring to ESP8266

BME280ESP8266
SCK (SCL Pin) GPIO 5
SDI (SDA pin) GPIO 4

Assemble your circuit as in the next schematic diagram if you’re using an ESP8266 board (read complete Guide for ESP8266 with BME280).

BME280 wiring to ESP8266

Recommended reading: ESP8266 Pinout Reference Guide

ESP32/ESP8266 Sketch

We’ll program the ESP32/ESP8266 using Arduino IDE, so you must have the ESP32/ESP8266 add-on installed in your Arduino IDE. Follow one of the next tutorials depending on the board you’re using:

After installing the necessary board add-ons, copy the following code to your Arduino IDE, but don’t upload it yet. You need to make some changes to make it work for you.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-send-email-notification/
  
  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.
*/

#ifdef ESP32
  #include <WiFi.h>
  #include <HTTPClient.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESP8266HTTPClient.h>
  #include <WiFiClient.h>
#endif

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// REPLACE with your Domain name with URL path or IP address with path
const char* serverName = "http://example.com/email-notification.php";

// Keep this API Key value to be compatible with the PHP code provided in the project page. 
// If you change the apiKeyValue value, the PHP file /email-notification.php also needs to have the same key 
String apiKeyValue = "tPmAT5Ab3j7F9";

/*#include <SPI.h>
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/

Adafruit_BME280 bme;  // I2C
//Adafruit_BME280 bme(BME_CS);  // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK);  // software SPI

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());

  // (you can also pass in a Wire library object like &Wire2)
  bool status = bme.begin(0x76);
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring or change I2C address!");
    while (1);
  }

  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    HTTPClient http;
    
    // Your Domain name with URL path or IP address with path
    http.begin(serverName);
    
    // Specify content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    // Prepare your HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(bme.readTemperature())
                           + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);
    
    // You can comment the httpRequestData variable above
    // then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
    //String httpRequestData = "api_key=tPmAT5Ab3j7F9&value1=24.75&value2=49.54&value3=1005.14";

    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);
     
    // If you need an HTTP request with a content type: application/json, use the following:
    //http.addHeader("Content-Type", "application/json");
    //int httpResponseCode = http.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");
    
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }

  // Use deep sleep to make the ESP send an email every X number of minutes/hours with low power consumption
  // ESP32 Deep Sleep Guide: https://RandomNerdTutorials.com/esp32-deep-sleep-arduino-ide-wake-up-sources/
  // ESP8266 Deep Sleep Guide: https://RandomNerdTutorials.com/esp8266-deep-sleep-with-arduino-ide/
}

void loop() {

}

View raw code

Setting your network credentials

You need to modify the following lines with your network credentials: SSID and password. The code is well commented on where you should make the changes.

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting your serverName

You also need to type your domain name, so the ESP publishes the readings to your own server.

const char* serverName = "http://example.com/email-notification.php";

Now, you can upload the code to your board. It should work straight away both in the ESP32 or ESP8266 board. If you want to learn how the code works, read the next section.

How the code works

Here’s a quick summary on how the code works:

  • Import all the libraries to make it work (it will import either the ESP32 or ESP8266 libraries based on the selected board in your Arduino IDE);
  • Set variables that you might want to change (apiKeyValue);
  • The apiKeyValue is just a random string that you can modify. It’s used for security reasons, so only anyone that knows your API key can send email notifications.
  • Initialize the serial communication for debugging purposes;
  • Establish a Wi-Fi connection with your router;
  • Initialize the BME280 sensor to get temperature, humidity and pressure readings;

Then, in the rest of the setup() is where you actually make the HTTP POST with the latest BME280 readings:

// Your Domain name with URL path or IP address with path
http.begin(serverName);

// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");

// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(bme.readTemperature())
                       + "&value2=" + String(bme.readHumidity()) + "&value3=" + String(bme.readPressure()/100.0F) + "";

int httpResponseCode = http.POST(httpRequestData);

You can comment the httpRequestData variable above that concatenates all the BME280 readings and use the httpRequestData variable below for testing purposes:

String httpRequestData = "api_key=tPmAT5Ab3j7F9&value1=24.75&value2=49.54&value3=1005.14";

Demonstration

After completing all the steps, power your ESP board and let it make an HTTP request to your server:

ESP32 BME280 Arduino IDE MySQL

If everything is working properly, this is what you should see in your Arduino IDE Serial Monitor:

ESP32 ESP8266 Send Email Arduino IDE Serial Monitor

Open your email client, you should have a new email with subject “[NEW] ESP BME280 Readings” with the latest temperature readings:

ESP32 ESP8266 Send Email Notification using PHP temperature humidity pressure

To send a new email, press the ESP on-board RESET/ENABLE button to restart it and new readings will be sent out via email.

For a final application, I recommend using deep sleep to make the ESP send an email every X number of minutes/hours with low power consumption. Read one of these guides to add deep sleep to your sketch:

Enable Threshold Notification

Finally, keep in mind that every time you restart your ESP (or the ESP wakes from deep sleep), it will send a new email notification with the current values. It might be useful setting a threshold value so that you only receive an email notification when your readings are above or below the threshold.

In your PHP script (email-notification.php), uncomment the following if statement:

// Uncomment the next if statement to set a threshold 
// ($value1 = temperature, $value2 = humidity, $value3 = pressure)
/*if($value1 < 24.0){
    echo "Temperature below threshold, don't send email";
    exit;
}*/

It will look like this:

// Uncomment the next if statement to set a threshold 
// ($value1 = temperature, $value2 = humidity, $value3 = pressure)
if($value1 < 24.0){
    echo "Temperature below threshold, don't send email";
    exit;
}

You can modify that if statement with the value type and only send an email based on that condition. With the current code, it will only send an email notification when the temperature is above 24.0ºC.

Wrapping Up

In this tutorial you’ve learned how to send emails with the ESP32 and ESP8266 using your own server and domain name.

The example provided is as simple as possible so that you can understand how everything works. After understanding this example, you may change the email content, publish different sensor readings, use multiple ESP boards, and much more.

You might also like reading:

I hope you liked this project. If you have any questions, post a comment below and we’ll try to get back to you.

If you like ESP32, you can enroll in our course “Learn ESP32 with Arduino IDE“. You can also access our free ESP32 resources here.

Thank you for reading.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

2 thoughts on “ESP32/ESP8266 Send Email Notification using PHP Script”

  1. Hi Rui,
    thank you (again) for another nice tutorial.
    If the emailing requires such complicated procedure (with fees involved), wouldn’t it be more practical to use Whatsapp messaging?

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.