In this project, you’ll build an ESP32 or ESP8266 customer that makes an HTTP POST request to a PHP manuscript to send an e-mail notice with sensor analyses.
Updated on 27 March 2023
You can additionally set a threshold value, so your e-mail notice is just sent if the temperature/humidity/pressure is over a certain value.
As an instance, we’ll be utilizing a BME280 sensing unit linked to an ESP32 or ESP8266 board. You can customize the code given to send analyses from a different sensor or even utilize several boards.
This is a fantastic way to send e-mail notices utilizing the ESP32 or ESP8266 without relying on IFTTT or an SMTP web server.
In order to develop this project, you will certainly:
This task is also a fantastic enhancement to build on our previous projects:
1. Hosting Your PHP Application
The goal of this project is to have your very own domain and hosting account that enables you to send out email notifications (without utilizing an SMTP web server, IFTTT, and so on……).
Here’s a high-level overview of how the project functions:
I recommend using among the adhering to organizing services that can handle all the task demands:
- : free domain name when you sign up for the 3-year plan. I recommend choosing the unlimited websites option;
- : Linux server that you manage through a command line. I only recommended this option for advanced users.
Those 2 solutions are the ones that I make use of as well as personally suggest, yet you can use any type of various other organizing solution. Any organizing service that offers PHP as well as MySQL will deal with this tutorial. If you don’t have an organizing account, I advise.
When getting a holding account, you’ll additionally have to buy a domain name. If you like our tasks, you could take into consideration enrolling in among the suggested hosting services, since you’ll be sustaining our work.
Note: you can also run a on a Raspberry Pi, yet it can’t send emails standalone. To send an e-mail 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 authorizing up for a, you can login to your cPanel or comparable dashboard.
After that, follow the following steps to produce a PHP script that is in charge of receiving inbound requests from the ESP32/ESP8266 as well as sending out an e-mail.
If you’re utilizing a hosting company with cPanel, most likely to Advanced and search for “File Manager”:
Then, choose the public_html alternative and press the “+ File” button to produce a new.php file.
Note: if you’re following this tutorial and also you’re not acquainted with PHP, I suggest creating that specific documents. Otherwise, you’ll need to change the ESP illustration offered with a different URL course.
Create a brand-new file in/ public_html with this specific name and expansion: email-notification. php
Edit the newly produced file (email-notification. php) as well as replicate the complying with 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 = "[email protected]";
// 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;
}
Before saving the file, you require to modify the $email_address variable with the receiver email address:
// Receiver Email Address (where to send email notification)
$email_address = "[email protected]";
After including the receiver e-mail, continue as well as save the file with this tutorial. If you attempt to access your domain in the next URL course, you’ll see the following:
https://example.com/email-notification.php
If you see that message, it suggests that every little thing is being setup correctly. You can continue with this job.
3. Setting Up Your ESP32 or ESP8266
This task works with both the ESP32 and ESP8266 boards. You simply require to assemble a simple circuit as well as submit the sketch supplied to release humidity, temperature, and also pressure readings to your PHP manuscript, which will certainly then be accountable to deal with e-mail alerts. The sketch is slightly various for every board.
Parts Required
For this instance, we’ll obtain sensing unit readings from the BME280 sensor. Here’s a checklist of components you require to build the circuit for this job:
- (read )
- Alternative – board (read )
You can utilize the coming before web links or go straight to locate all the parts for your projects at the very best rate!
Schematics
The BME280 sensor component we’re making use of connects by means of I2C interaction method, so you need to link it to the ESP32 or ESP8266 I2C pins.
BME280 wiring to ESP32
BME280 | ESP32 |
SCK (SCL Pin) | GPIO 22 |
SDI (SDA pin) | GPIO 21 |
So, assemble your circuit as received the next schematic diagram ().
Recommended reading:
BME280 wiring to ESP8266
BME280 | ESP8266 |
SCK (SCL Pin) | GPIO 5 |
SDI (SDA pin) | GPIO 4 |
Assemble your circuit as in the next schematic representation if you’re utilizing an ESP8266 board ().
Recommended reading:
Installing Libraries
We’ll configure the ESP32/ESP8266 using Arduino IDE, so you need to have the ESP32/ESP8266 add-on set up in your Arduino IDE. Adhere to among the next tutorials depending upon the board you’re using:
- – you also need to and
- – you also need to and
ESP32 Code
Follow this area if you’re utilizing an ESP32..
After setting up the required board add-ons, duplicate the complying with code to your Arduino IDE, but do not publish it yet. You need to make some modifications 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.
*/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "https://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*/
#define SEALEVELPRESSURE_HPA (1013.25)
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){
WiFiClientSecure *client = new WiFiClientSecure;
client->setInsecure(); //don't use SSL certificate
HTTPClient https;
// Your Domain name with URL path or IP address with path
https.begin(*client, serverName);
// Specify content-type header
https.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&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";
// Send HTTP POST request
int httpResponseCode = https.POST(httpRequestData);
// If you need an HTTP request with a content type: text/plain
//https.addHeader("Content-Type", "text/plain");
//int httpResponseCode = https.POST("Hello, World!");
// If you need an HTTP request with a content type: application/json, use the following:
//https.addHeader("Content-Type", "application/json");
//int httpResponseCode = https.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
https.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/
}
void loop() {
}
Setting your network credentials
You need to modify the complying with lines with your network credentials: SSID and also password. The code is well talked about where you should make the adjustments.
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Setting your serverName
You likewise require to type your domain name, so the ESP releases the readings to your own web server.
const char* serverName = "https://example.com/email-notification.php";
Now, you can publish the code to your board.
Note: Most servers require you to make HTTPS demands. The code above makes HTTPS requests to be compliant with the needs of many cloud web servers nowadays.
Your web server does not sustain HTTPS?.
How the code works
Here’s a fast summary of exactly 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;
- Initialize a secure WiFi client.
Then, in the remainder of the configuration() is where you in fact make the HTTP POST with the most up to date BME280 analyses:
// Your Domain name with URL path or IP address with path
http.begin(client, 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 as well as use the httpRequestData variable listed below for testing functions:
String httpRequestData = "api_key=tPmAT5Ab3j7F9&value1=24.75&value2=49.54&value3=1005.14";
Learn more concerning HTTPS Requests with the ESP32:.
ESP8266 Code
Follow this section if you’re making use of an ESP8266..
After mounting the necessary board attachments, replicate the adhering to code to your Arduino IDE, but don’t publish it yet. You need to make some adjustments to make it help 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.
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "https://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*/
#define SEALEVELPRESSURE_HPA (1013.25)
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){
std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
// Ignore SSL certificate validation
client->setInsecure();
//create an HTTPClient instance
HTTPClient https;
// Your Domain name with URL path or IP address with path
https.begin(*client, serverName);
// Specify content-type header
https.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&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";
// Send HTTP POST request
int httpResponseCode = https.POST(httpRequestData);
// If you need an HTTP request with a content type: text/plain
//http.addHeader("Content-Type", "text/plain");
//int httpResponseCode = https.POST("Hello, World!");
// If you need an HTTP request with a content type: application/json, use the following:
//http.addHeader("Content-Type", "application/json");
//int httpResponseCode = https.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
https.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
// ESP8266 Deep Sleep Guide: https://RandomNerdTutorials.com/esp8266-deep-sleep-with-arduino-ide/
}
void loop() {
}
Setting your network credentials
You need to modify the following lines with your network qualifications: SSID as well as password. The code is well commented on where you ought to make the modifications.
// 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 kind your domain, so the ESP releases the analyses to your own server.
const char* serverName = "https://example.com/email-notification.php";
Now, you can submit the code to your board.
Note: Most servers need you to make HTTPS requests. The code above makes HTTPS demands to be compliant with the requirements of most cloud web servers nowadays.
Your server does not sustain HTTPS?.
Learn more concerning HTTPS Requests with the ESP8266:.
Demonstration
After completing all the steps, power your ESP board and also let it make an HTTP demand to your server:
If whatever is working appropriately, this is what you ought to see in your Arduino IDE Serial Monitor:
Open your e-mail client, you ought to have a new e-mail with the subject” [BRAND-NEW] ESP BME280 Readings” with the current temperature analyses:
To send a new email, press the ESP on-board RESET/ENABLE switch to reboot it and also new analyses will certainly be sent out using email.
For a last application, I advise using deep rest to make the ESP send out an email every X variety of minutes/hours with reduced power intake. Check out one of these overviews to add deep sleep to your illustration:
Enable Threshold Notification
Finally, bear in mind that every single time you restart your ESP (or the ESP wakes from deep sleep), it will certainly send a new e-mail alert with the existing worths. When your readings are over or below the threshold, it might be helpful to set a threshold value so that you only get an email notification.
In your PHP manuscript (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 appear 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 customize that if declaration with the worth limit as well as just send an e-mail based upon that condition. With the existing code, it will just send out an e-mail notice when the temperature level is above 24.0 ºC.
Wrapping Up
In this tutorial you’ve discovered how to send e-mails with the ESP32 as well as ESP8266 using your own.
The instance supplied is as straightforward as feasible to ensure that you can recognize just how whatever works. After comprehending this instance, you may transform the email content, release different sensing unit readings, make use of multiple ESP boards, and a lot more.
You might additionally like analysis:
Learn more about the ESP32 with our resources:
Thank you for analysis.