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.

ESP32 Send Emails using an SMTP Server: HTML, Text and Attachments with Arduino IDEhttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-Send-Emails-SMTP-Server-HTML-Text-Attachments-Arduino-IDE.jpg?resize=300%2C169&ssl=1 300w, https://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-Send-Emails-SMTP-Server-HTML-Text-Attachments-Arduino-IDE.jpg?resize=1024%2C576&ssl=1 1024w, https://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-Send-Emails-SMTP-Server-HTML-Text-Attachments-Arduino-IDE.jpg?resize=768%2C432&ssl=1 768w" sizes="(max-width: 813px) 100vw, 813px" width="699" height="393" data-reader-unique-id="6" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 699px; margin-inline-start: -26.453125px;">

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.

Install library ESP32 Send Email SMTP Server Arduino IDEhttps://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/Install-library-ESP32-Send-Email-SMTP-Server.png?resize=300%2C169&ssl=1 300w, https://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/Install-library-ESP32-Send-Email-SMTP-Server.png?resize=768%2C433&ssl=1 768w" sizes="(max-width: 723px) 100vw, 723px" data-reader-unique-id="34" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 699px; margin-inline-start: -26.453125px;">

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.

Gmail Create a new accounthttps://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/GMAIL-create-a-new-account.png?resize=300%2C192&ssl=1 300w, https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/GMAIL-create-a-new-account.png?resize=768%2C492&ssl=1 768w" sizes="(max-width: 813px) 100vw, 813px" width="699" height="448" data-reader-unique-id="48" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 699px; margin-inline-start: -26.453125px;">

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 Allow Less Secure Apps to Send Email with ESP32https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/GMAIL-Allow-Less-Secure-Apps-to-Send-Email-with-ESP32.png?resize=300%2C186&ssl=1 300w, https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/GMAIL-Allow-Less-Secure-Apps-to-Send-Email-with-ESP32.png?resize=768%2C477&ssl=1 768w" sizes="(max-width: 802px) 100vw, 802px" width="699" height="434" data-reader-unique-id="64" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 699px; margin-inline-start: -26.453125px;">

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

View raw code

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.

ESP32 SMTP Server Send Email with Text Arduino IDE Serial Monitorhttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Send-Email-with-Text-Arduino-IDE-Serial-Monitor.png?resize=300%2C237&ssl=1 300w, https://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Send-Email-with-Text-Arduino-IDE-Serial-Monitor.png?resize=768%2C606&ssl=1 768w" sizes="(max-width: 803px) 100vw, 803px" width="699" height="552" data-reader-unique-id="540" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 699px; margin-inline-start: -26.453125px;">

Check your email account. You should have received an email from your ESP32 board.

ESP32 SMTP Server Receive Email Testhttps://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Receive-Email-Test.png?resize=300%2C76&ssl=1 300w, https://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Receive-Email-Test.png?resize=768%2C194&ssl=1 768w" sizes="(max-width: 813px) 100vw, 813px" data-recalc-dims="1" data-reader-unique-id="546" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 786.09375px; margin-inline-start: -70px;">

If you set the option to send a message with HTML text, this is how the message looks like:

ESP32 SMTP Server Send Email with Body Text format HTMLhttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Send-Email-with-Body-Text-format-HTML.png?resize=300%2C163&ssl=1 300w" sizes="(max-width: 601px) 100vw, 601px" width="601" height="327" data-reader-unique-id="550" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

If you’ve enable the raw text message, this is the email that you should receive.

ESP32 SMTP Server Send Email with Body Text only formathttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Send-Email-with-Body-Text-only-format.png?resize=300%2C147&ssl=1 300w" sizes="(max-width: 570px) 100vw, 570px" width="570" height="280" data-reader-unique-id="556" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

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:

Upload the files to SPIFFS to send as an email attachment

Your folder structure should look as follows (download project folder):

Folder structure files SPIFFS send attachments via email with ESP32https://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/folder-structure-files-spiffs-send-via-email.png?resize=300%2C192&ssl=1 300w" sizes="(max-width: 559px) 100vw, 559px" width="559" height="357" data-reader-unique-id="595" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

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. 

ESP32 Sketch Data Upload Arduino IDE SPIFFS FS Filesystemhttps://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2018/10/sketch-data-upload.png?resize=226%2C300&ssl=1 226w" sizes="(max-width: 295px) 100vw, 295px" width="295" height="391" data-reader-unique-id="602" style="max-width: 100%; margin: 0.5em auto; display: block; height: auto;">

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

View raw code

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.

ESP32 SMTP Server Send Email with attachments Arduino IDE Serial Monitorhttps://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Send-Email-with-attachments-Arduino-IDE-Serial-Monitor.png?resize=300%2C223&ssl=1 300w, https://i2.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Send-Email-with-attachments-Arduino-IDE-Serial-Monitor.png?resize=768%2C570&ssl=1 768w" sizes="(max-width: 803px) 100vw, 803px" width="699" height="519" data-reader-unique-id="950" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 699px; margin-inline-start: -26.453125px;">

Check the recipient’s email address. You should have a new email with two attachments.

ESP32 Send an Email with Attachment Programmed using Arduino IDEhttps://i0.wp.com/randomnerdtutorials.com/wp-content/uploads/2020/02/ESP32-SMTP-Server-Send-Email-with-attachemnts-test-1.png?resize=300%2C201&ssl=1 300w" sizes="(max-width: 704px) 100vw, 704px" width="699" height="469" data-reader-unique-id="954" class="extendsBeyondTextColumn" style="max-width: none; margin: 0.5em auto; display: block; height: auto; width: 699px; margin-inline-start: -26.453125px;">

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-CAMuse 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 »