ESP8266 Send Emails (Plain text, HTML, and Attachments) through SMTP Server

In this user guide, we will learn how to send emails using ESP8266 NodeMCU development board through an SMTP server and Arduino IDE. We will learn to incorporate different types of emails. The message body of the email will consist of plain text, HTML text, and attachments like images. We will introduce all three types in this guide.

ESP8266 NodeMCU Send Emails through SMTP Server Arduino IDE

We have a similar guide with ESP32:

ESP32 Send Emails (Plain text, HTML, and Attachments) through SMTP Server

Prerequisites

We will use Arduino IDE to program our ESP8266 development board. Thus, you should have the latest version of Arduino IDE. Additionally, you also need to install the ESP8266 plugin. If your IDE does not have the plugin installed you can visit the link below:

Installing ESP8266 library in Arduino IDE

In this tutorial, we learn two examples:

  • Sending plain text and HTML email
  • ESP8266 send attachments (Images + Files) with email

SMTP Server Introduction

Simple Mail Transfer Protocol server or SMTP server for short is responsible for sending and receiving emails between the senders and the receivers. Each email provider e.g., Gmail, Yahoo, Hotmail, Outlook, etc. has a unique SMTP address and settings. These can usually be accessed through your account settings. Whenever a user sends an email, the SMTP server processes it and sends it to the particular server accordingly. The recipient’s email service provides obtains the message which then turns up in the recipient’s inbox.

Sending Email using ESP8266

To send an email using ESP8266 through an SMTP server you will require the following:

  • ESP Mail Client Library
  • The sender’s email address
  • Recipient’s email address
  • Email content: The message body can be sent as plain text or as HTML text. We will cover simple text, HTML and attachments.

Installing ESP Mail Client Library

To use SMTP with our ESP board we will require a library. We will install the ESP Mail Client library from Github. To download the library, click here. Click on ‘Code’ and then ‘Download Zip’.

ESP Mail Client library
Install Library

You will download the library as a .zip folder which you will extract and rename as ‘ESP_Mail_Client.h’. Then, transfer this folder to the installation library folder in your Arduino IDE. Likewise, you can also go to Sketch > Include Library > Add .zip Library inside the IDE to add the library as well. After installation of the library, restart your IDE.

With the help of this library, the user can send/receive emails using the ESP8266 board easily.

Setting up Gmail Account

As discussed above, to send emails using our ESP8266 board we would require two email accounts. One for the sender and one for the recipient. You can use your own email account as the sender account but it is recommended to create a new one just in case something goes wrong in the program code. For this article, we will use Gmail as the primary email provider. You can use any other provider as your preference.

Creating a new account in Gmail (Sender side) for ESP8266

For this tutorial, we have created a new Gmail account and we also recommend you create a new Gmail account. Because if something wrong happens with your ESP8266 code and you may incidentally make too many email requests from your personal account, Google may ban your account or block it temporarily. The receiver’s email address can be your personal email address.

To create a Google account:

  • Go to the Google Sign Up page: https://www.google.com/gmail/about/ in the required information, such as first and last name, desired email address, password, phone number, and date of birth.
  • Click “Next” to proceed with the verification process.
  • Read and accept the terms of service and privacy policy.
  • Click “Create Account.”
Setting new gmail account 1

Now type all the relevant information and click ‘Next’. You can give in details according to your preference.

Setting new gmail account 2

Proceed with all the steps accordingly to create your account successfully.

Create an App Password

To send an email with ESP8266, first, you need to create an App password using your Gmail account. An app password in Gmail is a unique password generated for an app or device that does not support 2-step verification. When 2-step verification is enabled for a Gmail account, users are required to enter a verification code in addition to their password when signing in. However, some apps or devices may not be able to prompt for the verification code. In these cases, users can generate an app password to use instead of their regular password for accessing Gmail on the app or device. The app password is only valid for a specific app or device and can be revoked at any time from the Google Account security settings.

First, enable 2-step verification on your account by following these steps:

  • Log in to your Google Account.
  • Go to the “Security” section in your Google Account settings.
  • Scroll down to “Signing in to Google.”
  • Under “2-Step Verification,” click “Get Started.”
  • Follow the prompts to set up 2-step authentication, which may include adding a phone number to receive verification codes via text or voice call.
  • After setting up 2-step authentication, you will be prompted to enter a verification code whenever you sign in to your Google Account on a new device or browse

To get an app password:

Log in to your Google Account and Go to the “Security” section in your Google Account settings.

get app password gmail

Scroll down to “Signing in to Google.” and Click “App Passwords.”

get app password gmail 1

Follow the prompts to generate a unique password for the app you want to use with your Google Account. From the select app field, chose mail and device as other. Give any name to this device. After that click on generate.

It will generate an app password for this specific device. Save this for later use. Because we will use it inside our code instead of the Gmail password.

get app password gmail 2

SMTP Server Settings for Gmail Server

You can view the Gmail server settings as shown below. Knowing this is important because we have to include them in our program code to configure our account properly.

  • Server: smtp.gmail.com
  • Sender username: the complete email address of the sender account.
  • Sender password: the password of the sender account
  • Server port (TLS): 587
  • Server port (SSL): 465
  • SMTP TLS/SSL required: yes

If you are using a different email provider e.g., outlook or yahoo you can access its SMTP server settings online.

Sending HTML and Plain Text Email with ESP8266

First let’s see an example to send plain text and HTML through an email ESP8266 using Arduino.

Arduino Sketch: Sending Plain Text Email

Open your Arduino IDE and go to File > New to open a new file. Copy the code given below in that file. You need to enter your network credentials. Additionally, you also have to provide your SMTP server parameters, the sender’s email details and the recipient’s email address.

This Arduino sketch will send an email through the SMTP server whenever the ESP8266 board boots.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP_Mail_Client.h>

#define WIFI_SSID "Your_SSID"
#define WIFI_PASSWORD "Your_Password"

#define SMTP_server "smtp.gmail.com"
#define SMTP_Port 465


#define sender_email "Write_Sender_Email_address"
#define sender_password "Write_Sender_Email_Password"

#define Recipient_email "Write_recipient_Email_address"


SMTPSession smtp;

void setup(){
  Serial.begin(115200);
  Serial.println();
  Serial.print("Connecting...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(200);
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  smtp.debug(1);


  ESP_Mail_Session session;


  session.server.host_name = SMTP_server ;
  session.server.port = SMTP_Port;
  session.login.email = sender_email;
  session.login.password = sender_password;
  session.login.user_domain = "";

  /* Declare the message class */
  SMTP_Message message;


  message.sender.name = "ESP8266";
  message.sender.email = sender_email;
  message.subject = "ESP8266 Testing Email";
  message.addRecipient("Microcontrollerslab",Recipient_email);

   //Send HTML message
  String htmlMsg = "<div style=\"color:#0000FF;\"><h1>Hello Microcontrollerslab!</h1><p>This is an HTML email sent from ESP Board</p></div>";
  message.html.content = htmlMsg.c_str();
  message.html.content = htmlMsg.c_str();
  message.text.charSet = "us-ascii";
  message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit; 

 /* 
  //Send simple text message
  String textMsg = "Hello Microcontrollerslab! This is a simple text sent from ESP board";
  message.text.content = textMsg.c_str();
  message.text.charSet = "us-ascii";
  message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit; */


  if (!smtp.connect(&session))
    return;


  if (!MailClient.sendMail(&smtp, &message))
    Serial.println("Error sending Email, " + smtp.errorReason());
 
}

void loop(){

}

How the Code Works?

Firstly, we will include the necessary libraries required for this project. ESP8266WiFi.h will help in establishing the connection between the ESP8266 module to a wireless network. We will also include the ESP Mail Client library to successfully send emails via the SMTP server.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP_Mail_Client.h>
Defining Network credentials

Next, we will define the network credentials. One for the SSID and the other for the password. These will be our network credentials which will be used to connect to our wireless network. Replace both of them with your credentials to ensure a successful connection.

#define WIFI_SSID "Your_SSID"
#define WIFI_PASSWORD "Your_Password"
Defining Server Settings

Next, we will define the server settings as shown below. We will specify the SMTP server, port, the sender’s email address, and its password. The sender’s account details are the ones which we newly created. Make sure that you have granted access to less secure apps for the sender account.

#define SMTP_server "smtp.gmail.com"
#define SMTP_Port 465
#define sender_email "Write_Sender_Email_address"
#define sender_password "Write_Sender_Email_Password"
Defining Recipient Account

Now give the complete email address of the account you want to send the email to.

#define Recipient_email "Write_recipient_Email_address"
Setup() function

Inside the setup() function, we will open a serial connection at a baud rate of 115200.

Serial.begin(115200);

The following section of code will connect our ESP8266 board with the local network whose network credentials we already specified above. We will use the WiFi.begin() function. The arguments will be the SSID and the password which we defined earlier in the code.

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(200);
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
Configuring Session

We will configure our session by specifying the details of the server as shown below. All of the parameters were defined earlier on in the code.

  session.server.host_name = SMTP_server ;
  session.server.port = SMTP_Port;
  session.login.email = sender_email;
  session.login.password = sender_password;
  session.login.user_domain = "";
Setting the Message Header

The following lines of code specify the contents of the message header. It will consist of the sender’s name, the sender’s email, and the subject of the email. You can give the subject according to your choice.

  message.sender.name = "ESP8266";
  message.sender.email = sender_email;
  message.subject = "ESP8266 Testing Email";
  message.addRecipient("Microcontrollerslab",Recipient_email);
HTML message body

The following lines of code define the HTML text body. For the heading we are specifying ‘Hello Microcontrollerslab!’. The next line will consist of ‘This is an HTML email sent from ESP Board’. This message will in blue colour as we have specified that as well. You can add your own HTML text and settings according to your preference.

String htmlMsg = "<div style=\"color:#0000FF;\"><h1>Hello Microcontrollerslab!</h1><p>This is an HTML email sent from ESP Board</p></div>";
  message.html.content = htmlMsg.c_str();
  message.html.content = htmlMsg.c_str();
  message.text.charSet = "us-ascii";
  message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
Simple Text Message body

If you want to send the email as a simple text then uncomment the block of code given below. Comment the HTML text block which was described above. We will specify the same message but this time it will be sent as a simple text.

  String textMsg = "Hello Microcontrollerslab! This is a simple text sent from ESP board";
  message.text.content = textMsg.c_str();
  message.text.charSet = "us-ascii";
  message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

The following lines will start the connection and send the email.

if (!smtp.connect(&session))
    return;
if (!MailClient.sendMail(&smtp, &message))
    Serial.println("Error sending Email, " + smtp.errorReason());

Demonstration

Choose the correct board and COM port before uploading your code to the board.
Go to Tools > Board and select NodeMCU 1.0

select ESP8266 NodeMCU board

Next, go to Tools > Port and select the appropriate port through which your board is connected.

ESP8266 COM Port

Click on the upload button to upload the code to your ESP8266 development board.
After you have uploaded your code to the development board, press its RST button.

ESP8266 NodeMCU reset button
Press RST Button

In your Arduino IDE, open up the serial monitor and you will be able to see the status of your WIFI connection and several other details.

ESP8266 email via SMTP server serial monitor demo simple text
Serial Monitor

Open the recipient’s email account. You will already have received the email from your ESP8266 module. For HTML text, the following email was received:

ESP8266 email via SMTP server demo HTML text

If you sent a simple text then the following email will be received.

ESP8266 email via SMTP server demo simple text

Sending Email Attachments with ESP8266

Now, we will look at another type of email that we can send from our ESP8266 board via the SMTP server. Besides, a text message body which we previously learnt how to send now let us move ahead and learn how to send attachments. We will send a .txt file and a .png image file. We will save both of these files in the flash (LittleFS) of the ESP8266.

Recommended Readings regarding LittleFS:

Displaying Images in ESP32 and ESP8266 Web Server

ESP8266 NodeMCU Web Server using LittleFS (Flash File System)

Setting up Arduino IDE

Filesystem Uploader Plugin

You will have to download and install the ESP8266 NodeMCU Filesystem Uploader Plugin in your Arduino IDE so that you are able to upload the LittleFS files on your ESP8266 NodeMCU board. If you haven’t, you can follow this tutorial:

LittleFS Introduction & Install ESP8266 NodeMCU Filesystem Uploader in Arduino IDE

Editing the ESP Mail Client Library for LittleFS

By default the ESP Mail Client library uses SPIFFS filesystem but as we are programming using ESP8266 hence we will require LittleFS instead. To use LittleFS with ESP Mail Client library we will have to edit the library file.

Go to Documents > Arduino > libraries and find ESP-Mail-Client-master. Click it to find the ESP_Mail_FS.h file and open it using note pad. We will edit this part of the code highlighted in red.

ESP8266 email via SMTP server editing esp mail client library pic1

We will edit it as shown in the picture below. Delete the lines that were highlighted in the red box above and include the ones that are highlighted in green. By including these lines we are making sure that the library uses SPIFFS for ESP32 and LittleFS for ESP8266 as default. Previously, it was using SPIFFS for both.

ESP8266 email via SMTP server editing esp mail client library pic2

Remember to save the file.

Arduino Sketch

Open your Arduino IDE and go to File > New to open a new file. Copy the code given below in that file. You need to enter your network credentials. Additionally, you also have to provide your SMTP server parameters, the sender’s email details and the recipient’s email address. You will also have to specify the name of your .txt file and .png file in the program code.

This Arduino sketch will send an email with two attachments (a text file and an image) through the SMTP server whenever the ESP8266 boots.

#include <Arduino.h>
#include <LittleFS.h>
#include <ESP8266WiFi.h>
#include <ESP_Mail_Client.h>

#define WIFI_SSID "Your_SSID"
#define WIFI_PASSWORD "Your_Password"

#define SMTP_server "smtp.gmail.com"
#define SMTP_Port 465

#define sender_email "Write_Sender_Email_address"
#define sender_password "Write_Sender_Email_password"

#define Recipient_email "Write_Recipient_Email_address"
SMTPSession smtp;

void setup(){
  Serial.begin(115200);
  Serial.println();
  Serial.print("Connecting...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(200);
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  // Initialize LittleFS
  if(!LittleFS.begin()){
    Serial.println("An Error has occurred while mounting LittleFS");
    return;
  }

  smtp.debug(1);

  ESP_Mail_Session session;

  session.server.host_name = SMTP_server ;
  session.server.port = SMTP_Port;
  session.login.email = sender_email;
  session.login.password = sender_password;
  session.login.user_domain = "mydomain.net";

  SMTP_Message message;

  message.enable.chunking = true;


  message.sender.name = "ESP8266";
  message.sender.email = sender_email;

  message.subject = "ESP8266 Testing Email with Attachments";
  message.addRecipient("Microcontrollerslab",Recipient_email);


  String htmlMsg = "This attachment message was sent by ESP8266 board";
  message.html.content = htmlMsg.c_str();
  message.html.charSet = "utf-8";
  message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;

  message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
  message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;

  SMTP_Attachment attachment;

  attachment.descr.filename = "image.png";
  message.resetAttachItem(attachment);
  attachment.descr.mime = "image/png"; 
  attachment.file.path = "/image.png";
  attachment.file.storage_type = esp_mail_file_storage_type_flash;
  attachment.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

  message.addAttachment(attachment);

  attachment.descr.filename = "File.txt";
  attachment.descr.mime = "text/plain";
  attachment.file.path = "/File.txt";
  attachment.file.storage_type = esp_mail_file_storage_type_flash;
  attachment.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

  message.addAttachment(attachment);
if (!smtp.connect(&session))
    return;

  if (!MailClient.sendMail(&smtp, &message, true))
    Serial.println("Error sending Email, " + smtp.errorReason());
}

void loop()
{
}

How does the Code work?

Most of the code is similar to the one which we discussed previously so we will look over the parts which are different.

After providing all the necessary details for a successful connection with the SMTP server, we will initialize the LittleFS.

  if(!LittleFS.begin()){
    Serial.println("An Error has occurred while mounting LittleFS");
    return;
  }

Next, we will create an attachment object. This will be used to specify the details of the two attachments. First, we will include the image file. This will consist of the file name, MIME type, file path and file storage type. Replace the name of your file and path destination with your parameters.

SMTP_Attachment attachment;
  attachment.descr.filename = "Your_image_file_name.png";
  attachment.descr.mime = "image/png"; 
  attachment.file.path = "/Your_image_file_name.png";
  attachment.file.storage_type = esp_mail_file_storage_type_flash;
  attachment.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

You can add this attachment to the message body through message.addAttachment(). This takes in the attachment object as the parameter inside it.

message.addAttachment(attachment);

To include further attachments, insert the following line of code:

message.resetAttachItem(attachment);

Similarly, we will give the information about the text file. Replace the name of your file and path destination with your own parameters.

attachment.descr.filename = "Your_text_file_name.txt";
  attachment.descr.mime = "text/plain";
  attachment.file.path = "/Your_text_file_name.txt";
  attachment.file.storage_type = esp_mail_file_storage_type_flash;
  attachment.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

This attachment will be attached with the message through the following line:

message.addAttachment(attachment);

The following lines will start the connection and send the email.

 if (!smtp.connect(&session))
    return;
 if (!MailClient.sendMail(&smtp, &message, true))
    Serial.println("Error sending Email, " + smtp.errorReason());

Uploading Files to ESP8266 LittleFS

Now follow the steps closely to ensure both the files are properly uploaded to the flash memory of your development board. We saved the Arduino sketch given above as ‘ESP8266_Email_Attachments.’ Choose the correct board and COM port. Go to Tools > Board and select NodeMCU 1.0. Next, go to Tools > Port and select the appropriate port through which your board is connected.

Before uploading to your ESP8266 board first go to Sketch > Show Sketch Folder.

This will open up the folder where your Arduino sketch is saved. Now create a new folder inside that folder and save it as ‘data.’

ESP8266 email via SMTP server LittleFS pic1

Place both the .txt and the .png file inside the data folder. Otherwise, the LittleFS library will not be able to read them.

ESP8266 email via SMTP server LittleFS pic2

The figure below shows how all the files should be placed:

ESP8266 email via SMTP server LittleFS pic3

Now, we will upload the files to our ESP8266 board. Go to Tools > ESP8266 LittleFS Data Upload.

LittleFS sketch data upload to esp8266 filesystem

After a few moments, the files will be uploaded. You will receive the message ‘LittleFS Image Uploaded’ on the debugging window.

LittleFS sketch data upload to filesystem

Demonstration

After you have uploaded your code and the files to the ESP8266 development board, press its RST button.
In your Arduino IDE, open up the serial monitor and you will be able to see the status of your WIFI connection and several other details.

ESP8266 email via SMTP server demo attachments serial monitor
Serial Monitor

Open the recipient’s email account. You will already have received the email from your ESP8266 module. The two attachments can be clearly seen.

ESP8266 email via SMTP server demo attachments

Conclusion

In conclusion, we learned how to send different types of emails using the ESP8266 board through the SMTP server. This can be highly useful to send sensor readings, publish data or transfer images using the development module.

8 thoughts on “ESP8266 Send Emails (Plain text, HTML, and Attachments) through SMTP Server”

  1. Is it actually working? I not familiar with Arduino but I have tried to send email using STM32. It looks like you can’t access gmail without SSL certificate from trusted authority. Am I missing something here? Are you accessing gmail with SSL?

    Reply
  2. Hi!

    I’ve got a problem:
    Error during sending is: set recipient failed
    And mail is not sent.
    I tried add mail address directly to message.addRecipient, #define mail, and nothing.
    I send mail via port 465 and 587 and nothong.

    Reply
  3. Hi, just compiling it on Arduino IDE1.8.19 it is showing “Error compiling for board NodeMCU 1.0 (ESP-12E Module). please advise

    Reply
  4. It would appear that ESP8266-mail-client now sets LittleFS as the default for 8266 boards. If you create a file within your sketch using SPIFFS, assuming that is the email default, email client can’t find and attach it. Be warned – it’s taken me 2 days to figure that one out!

    Reply

Leave a Comment