ESP32 Send Emails using an SMTP Server: HTML, Text and Attachments (Arduino IDE)
Learn how to send emails with the ESP32 using an SMTP Server. We’ll show you how to send a simple email with HTML or raw text and how to send attachments like images and files (.txt). The ESP32 board will be programmed using Arduino IDE.
You may also like reading: ESP32 / ESP8266 Send Email Notification using PHP Script
Introducing SMTP Servers
SMTP means Simple Mail Transfer Protocol and it is an internet standard for email transmission. To send emails using an ESP32, you need to connect it to an SMTP Server.
ESP32 MailClient Library
To send emails with the ESP32, we’ll use the ESP32 MailClient library. This library allows the ESP32 to send and receive emails with or without attachment via SMTP and IMAP servers.
In this tutorial we’ll use SMTP to send an email with and without attachments. As an example, we’ll send an image (.jpg) and a text (.txt) file. The files to be sent via email can be saved in the ESP32 SPIFFS or SD card.
Installing the ESP32 MailClient Library
Before proceeding with this tutorial, you need to install the ESP32 MailClient library. This library can be installed through the Arduino IDE Library Manager.
In your Arduino IDE go to Sketch > Include Library > Manage Libraries…
The Library Manager should open. Search for ESP32 Mail Client by Mobizt and install the library as shown below.
Sender Email (New Account)
We recommend creating a new email account to send the emails to your main personal email address. Do not use your main personal email to send emails via ESP32. If something goes wrong in your code or if by mistake you make too many requests, you can be banned or have your account temporary disabled.
We’ll use a newly created Gmail.com account to send the emails, but you can use any other email provider. The receiver email can be your personal email without any problem.
Create a Sender Email Account
Create a new email account for sending emails with the ESP32. If you want to use a Gmail account, go to this link to create a new one.
Allow less secure apps
Allow less secure apps to get access to this new Gmail account, so that you’re able to send emails. You can open this link to go to that menu.
Gmail SMTP Server Settings
If you’re using a Gmail account, these are the SMTP Server details:
- SMTP Server: smtp.gmail.com
- SMTP username: Complete Gmail address
- SMTP password: Your Gmail password
- SMTP port (TLS): 587
- SMTP port (SSL): 465
- SMTP TLS/SSL required: yes
Outlook SMTP Server Settings
For Outlook accounts, these are the SMTP Server settings:
- SMTP Server: smtp.office365.com
- SMTP Username: Complete Outlook email address
- SMTP Password: Your Outlook password
- SMTP Port: 587
- SMTP TLS/SSL Required: Yes
Live or Hotmail SMTP Server Settings
For Live or Hotmail accounts, these are the SMTP Server settings:
- SMTP Server: smtp.live.com
- SMTP Username: Complete Live/Hotmail email address
- SMTP Password: Your Windows Live Hotmail password
- SMTP Port: 587
- SMTP TLS/SSL Required: Yes
If you’re using another email provider, you need to search for its SMTP Server settings. Now, you have everything ready to start sending emails with your ESP32.
Send an Email with HTML or Raw Text with ESP32 (Arduino IDE)
The following code sends an email via SMTP Server with HTML or raw text. For demonstration purposes, the ESP32 sends an email once when it boots. Then, you should be able to modify the code and integrate it in your own projects.
Don’t upload the code yet, you need to make some modifications to make it work for you.
#include "ESP32_MailClient.h"
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
#define emailSenderAccount "Cette adresse courriel est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser."
#define emailSenderPassword "YOUR_EXAMPLE_EMAIL_PASSWORD"
#define emailRecipient "Cette adresse courriel est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser."
#define smtpServer "smtp.gmail.com"
#define smtpServerPort 465
#define emailSubject "ESP32 Test"
SMTPData smtpData;
void sendCallback(SendStatus info);
void setup(){
Serial.begin(115200);
Serial.println();
Serial.print("Connecting");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200);
}
Serial.println();
Serial.println("WiFi connected.");
Serial.println();
Serial.println("Preparing to send email");
Serial.println();
smtpData.setLogin(smtpServer, smtpServerPort, emailSenderAccount, emailSenderPassword);
smtpData.setSender("ESP32", emailSenderAccount);
smtpData.setPriority("High");
smtpData.setSubject(emailSubject);
smtpData.setMessage("<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent from ESP32 board</p></div>", true);
smtpData.addRecipient(emailRecipient);
smtpData.setSendCallback(sendCallback);
if (!MailClient.sendMail(smtpData))
Serial.println("Error sending Email, " + MailClient.smtpErrorReason());
smtpData.empty();
}
void loop() {
}
void sendCallback(SendStatus msg) {
Serial.println(msg.info());
if (msg.success()) {
Serial.println("----------------");
}
}
You need to insert your network credentials as well as setting the sender email, SMTP Server details, recipient and message.
How the Code Works
Include the ESP32_MailClient.h library.
#include "ESP32_MailClient.h"
Network credentials
Insert your network credentials in the following variables, so that the ESP32 is able to connect to the internet to send the emails.
const char* ssid = "RAPLACE_WITH_YOUR_SSID";
const char* password = "RAPLACE_WITH_YOUR_PASSWORD";
Email settings
Insert the email sender account on the emailSenderAccount variable and its password on the emailSenderPassword variable.
#define emailSenderAccount "Cette adresse courriel est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser."
#define emailSenderPassword "email_sender_password"
Insert the recipient email. This is the email that will receive the emails sent by the ESP32:
#define emailRecipient "Cette adresse courriel est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser."
Insert your email provider SMTP settings on the following lines (we’re using the settings for a Gmail account):
#define smtpServer "smtp.gmail.com"
#define smtpServerPort 465
Write the email subject on the emailSubject variable.
#define emailSubject "ESP32 Test"
Create an STMPData object called smtpData that contains the data to send via email and all the other configurations.
SMTPData smtpData;
setup()
In the setup(), connect the ESP32 to Wi-Fi.
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200);
}
The following line sets the SMTP Server host, SMTP port, account email address and password used to login:
smtpData.setLogin(smtpServer, smtpServerPort, emailSenderAccount, emailSenderPassword);
Set the sender name and sender email. In this case, we’re setting the sender name to ESP32.
smtpData.setSender("ESP32", emailSenderAccount);
Set the email priority.
smtpData.setPriority("High");
Set the email subject.
smtpData.setSubject(emailSubject);
The following line sets the message. You can send an HTML text or raw text. In this case, we’re sending a message with some HTML.
smtpData.setMessage("<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent from ESP32 board</p></div>", true);
When sending a message in HTML format, you should pass true as a second parameter to the setMessage() method. If you want to send raw text, set false.
Finally, set the recipient email. This is the email that will receive the messages from the ESP32.
smtpData.addRecipient(emailRecipient);
Now that we’ve set all the details of the smtpData, we’re ready to send the email.
if (!MailClient.sendMail(smtpData))
Serial.println("Error sending Email, " + MailClient.smtpErrorReason());
After sending the email, you can clear all the data from the smtpData object.
smtpData.empty();
In this example, the email is sent once when the ESP32 boots, that’s why the loop() is empty.
void loop() {
}
Demonstration
Upload the code to your ESP32. After uploading, open the Serial Monitor at a baud rate of 115200. Press the ESP32 Reset button.
If everything went as expected you should get a similar message in the Serial Monitor.
Check your email account. You should have received an email from your ESP32 board.
If you set the option to send a message with HTML text, this is how the message looks like:
If you’ve enable the raw text message, this is the email that you should receive.
Send Attachments via Email with ESP32 (Arduino IDE)
In this section, we’ll show you how to send attachments in your emails sent by the ESP32. We’ll show how to send .txt files or pictures. This can be useful to send a .txt file with sensor readings from the past few hours, or to send a photo captured by an ESP32-CAM.
The files to be sent should be saved on the ESP32 SPIFFS or in a microSD card. In this example, we’ll be using SPIFFS (but the code provided can be changed to use a microSD card).
Upload files to SPIFFS
To send files via email, these should be saved on the ESP32 SPIFFS, or in a microSD card. We’ll upload a picture and a .txt file to the ESP32 SPIFFS using the ESP32 Filesystem Uploader plugin for Arduino IDE. Follow the next tutorial to install the plugin if you don’t have it installed yet:
Create a new Arduino sketch and save it. Go to Sketch > Show Sketch folder. Inside the Arduino sketch folder, create a folder called data. Move a jpg file and .txt file to your data folder.
Alternatively, you can click here to download the project folder.
Note: with the default code your files must be named ESP32-CAM-Test.jpg and text_file.txt or you can modify the code to import files with a different name.
We’ll be sending these files:
Your folder structure should look as follows (download project folder):
After moving the files to the data folder, in your Arduino IDE, go to Tools > ESP32 Data Sketch Upload and wait for the files to be uploaded.
You should get a success message on the debugging window. If the files were successfully uploaded, move on to the next section.
Note: if you start seeing many dots ….____…..____ being printed on the debugging window, you need to hold the ESP32 on-board BOOT button for the files to be uploaded.
Code
The following code sends an email with a .txt file and a picture attached. Before uploading the code, make sure you insert your sender emails settings as well as your recipient email.
#include "ESP32_MailClient.h"
#include "SD.h"
#include "SPIFFS.h"
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
#define emailSenderAccount "Cette adresse courriel est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser."
#define emailSenderPassword "YOUR_EXAMPLE_EMAIL_PASSWORD"
#define emailRecipient "Cette adresse courriel est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser."
#define smtpServer "smtp.gmail.com"
#define smtpServerPort 465
#define emailSubject "ESP32 Test Email with Attachments"
SMTPData smtpData;
void sendCallback(SendStatus info);
void setup(){
Serial.begin(115200);
Serial.println();
if(!SPIFFS.begin(true)) {
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
Serial.print("Connecting");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(200);
}
Serial.println();
Serial.println("WiFi connected.");
Serial.println();
Serial.println("Preparing to send email");
Serial.println();
smtpData.setLogin(smtpServer, smtpServerPort, emailSenderAccount, emailSenderPassword);
smtpData.setSender("ESP32", emailSenderAccount);
smtpData.setPriority("High");
smtpData.setSubject(emailSubject);
smtpData.setMessage("<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent from ESP32 board</p></div>", true);
smtpData.addRecipient(emailRecipient);
smtpData.addAttachFile("/ESP32-CAM-Test.jpg", "image/jpg");
smtpData.addAttachFile("/text_file.txt");
smtpData.setFileStorageType(MailClientStorageType::SPIFFS);
smtpData.setSendCallback(sendCallback);
if (!MailClient.sendMail(smtpData))
Serial.println("Error sending Email, " + MailClient.smtpErrorReason());
smtpData.empty();
}
void loop() {
}
void sendCallback(SendStatus msg) {
Serial.println(msg.info());
if (msg.success()) {
Serial.println("----------------");
}
}
How the code works
This code is very similar to the previous one, so we’ll just take a look at the relevant parts to send attachments.
In the setup(), you need to initialize SPIFFS:
if(!SPIFFS.begin(true)) {
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
If you want to send files saved on the microSD card, uncomment the next lines (make sure you insert the right pin assignment for the microSD card):
Then, to attach a file, you just need to call the addAtatachFile() on the smtpDataobject and pass as argument the file path. For example, the image we’ll send is called ESP32-CAM-Test.jpg, so, send it as follows:
smtpData.addAttachFile("/ESP32-CAM-Test.jpg", "image/jpg");
The text file we want to send is called text_file.txt:
smtpData.addAttachFile("/text_file.txt");
If you want to send different files, you just need to change the path.
Finally, you need to set where your files are saved (SPIFFS or SD card). We’re using SPIFFS:
smtpData.setFileStorageType(MailClientStorageType::SPIFFS);
If you want to use SD card, comment the previous line and uncomment the following:
And that’s it! As you can see the code to send an attachment via email is very simple.
Demonstration
After uploading the code, open the Serial Monitor at a baud rate of 115200 and press the on-board EN/RESET button. If everything goes smoothly, you should get a similar message on the Serial Monitor.
Check the recipient’s email address. You should have a new email with two attachments.
Wrapping Up
In this tutorial you’ve learned how to send emails with the ESP32 using an SMTP Server. For this method to work, the ESP32 should have access to the internet.
If you don’t want to use an SMTP Server, you can also write a PHP script to send email notifications with the ESP32 or ESP8266 board.
You’ve learned how to send a simple email with text and with attachments. When using attachments, these should be save on an SD card or on SPIFFS.
The examples presented show how to send a single email when the ESP32 boots. The idea is to modify the code and include it in your own projects. For example, it can be useful to send a .txt file with the sensor readings, to send a photo captured with the ESP32-CAM, use deep sleep to wake up your board every hour and send an email with data, etc.
We hope you’ve find this tutorial interesting.
To learn more about the ESP32, take a look at our resources:
Thanks for reading.
Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »