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 (Arduino IDE)

Updated 14 June 2024

In this tutorial, we cover the following topics:

We have a similar tutorial for the ESP8266 board: ESP8266 NodeMCU Send Emails using an SMTP Server: HTML, Text, and Attachments (Arduino)

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.

ESP Mail Client Library

To send emails with the ESP32, we’ll use the ESP-Mail-Client library. This library allows the ESP32 to send and receive emails with or without attachments 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 (.png) and a text (.txt) file. The files sent via email can be saved in the ESP32 Filesystem (SPIFFS, LittleFS, or FatFs) or a microSD card (not covered in this tutorial).

Installing the ESP-Mail-Client Library

Before proceeding with this tutorial, you need to install the ESP-Mail-Client library.

Go to Sketch > Include Library > Manage Libraries and search for ESP Mail Client. Install the ESP Mail Client library by Mobizt.

Install ESP Mail Client Library Arduino IDE

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 temporarily 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 account

Create an App Password

You need to create an app password so that the ESP32 is able to send emails using your Gmail account. An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. Learn more about sign-in with app passwords here.

An app password can only be used with accounts that have 2-step verification turned on.

  1. Open your Google Account.
  2. In the search panel, select Security.
  3. Under “Signing in to Google,” select 2-Step Verification > Get started.
  4. Follow the on-screen steps.

After enabling 2-step verification, you can create an app password.

  1. Open your Google Account.
  2. In the search panel, search for App Passwords.
  3. Open the App Passwords menu.
Google - Create app password
  1. Give a name to the app password, for example ESP. Then, click on Create. It will pop-up a window with a password that you’ll use with the ESP32 or ESP8266 to send emails. Save that password (even though it says you won’t need to remember it) because you’ll need it later.
Create App password gmail

It will pop-up a window with a password that you’ll use with the ESP32 or ESP8266 to send emails. Save that password (even though it says you won’t need to remember it) because you’ll need it later.

Generated app password Gmail

Now, you should have an app password that you’ll use on the ESP code to send the emails.

App password created ESP32

If you’re using another email provider, check how to create an app password. You should be able to find the instructions with a quick google search “your_email_provider + create app password”.

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 into your own projects.

Don’t upload the code yet, you need to make some modifications to make it work for you.

/*
  Rui Santos
  Complete project details at:
   - ESP32: https://RandomNerdTutorials.com/esp32-send-email-smtp-server-arduino-ide/
   - ESP8266: https://RandomNerdTutorials.com/esp8266-nodemcu-send-email-smtp-server-arduino/
  
  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.
  Example adapted from: https://github.com/mobizt/ESP-Mail-Client
*/

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com */
#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT 465

/* The sign in credentials */
#define AUTHOR_EMAIL "[email protected]"
#define AUTHOR_PASSWORD "YOUR_EMAIL_APP_PASS"

/* Recipient's email*/
#define RECIPIENT_EMAIL "[email protected]"

/* Declare the global used SMTPSession object for SMTP transport */
SMTPSession smtp;

/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status);

void setup(){
  Serial.begin(115200);
  Serial.println();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  /*  Set the network reconnection option */
  MailClient.networkReconnect(true);

  /** Enable the debug via Serial port
   * 0 for no debugging
   * 1 for basic level debugging
   *
   * Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h
   */
  smtp.debug(1);

  /* Set the callback function to get the sending results */
  smtp.callback(smtpCallback);

  /* Declare the Session_Config for user defined session credentials */
  Session_Config config;

  /* Set the session config */
  config.server.host_name = SMTP_HOST;
  config.server.port = SMTP_PORT;
  config.login.email = AUTHOR_EMAIL;
  config.login.password = AUTHOR_PASSWORD;
  config.login.user_domain = "";

  /*
  Set the NTP config time
  For times east of the Prime Meridian use 0-12
  For times west of the Prime Meridian add 12 to the offset.
  Ex. American/Denver GMT would be -6. 6 + 12 = 18
  See https://en.wikipedia.org/wiki/Time_zone for a list of the GMT/UTC timezone offsets
  */
  config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
  config.time.gmt_offset = 3;
  config.time.day_light_offset = 0;

  /* Declare the message class */
  SMTP_Message message;

  /* Set the message headers */
  message.sender.name = F("ESP");
  message.sender.email = AUTHOR_EMAIL;
  message.subject = F("ESP Test Email");
  message.addRecipient(F("Sara"), RECIPIENT_EMAIL);
    
  /*Send HTML message*/
  /*String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- 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 raw text message
  String textMsg = "Hello World! - Sent from ESP board";
  message.text.content = textMsg.c_str();
  message.text.charSet = "us-ascii";
  message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
  
  message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
  message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;


  /* Connect to the server */
  if (!smtp.connect(&config)){
    ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
    return;
  }

  if (!smtp.isLoggedIn()){
    Serial.println("\nNot yet logged in.");
  }
  else{
    if (smtp.isAuthenticated())
      Serial.println("\nSuccessfully logged in.");
    else
      Serial.println("\nConnected with no Auth.");
  }

  /* Start sending Email and close the session */
  if (!MailClient.sendMail(&smtp, &message))
    ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());

}

void loop(){
}

/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status){
  /* Print the current status */
  Serial.println(status.info());

  /* Print the sending result */
  if (status.success()){
    // ESP_MAIL_PRINTF used in the examples is for format printing via debug Serial port
    // that works for all supported Arduino platform SDKs e.g. AVR, SAMD, ESP32 and ESP8266.
    // In ESP8266 and ESP32, you can use Serial.printf directly.

    Serial.println("----------------");
    ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());
    ESP_MAIL_PRINTF("Message sent failed: %d\n", status.failedCount());
    Serial.println("----------------\n");

    for (size_t i = 0; i < smtp.sendingResult.size(); i++)
    {
      /* Get the result item */
      SMTP_Result result = smtp.sendingResult.getItem(i);

      // In case, ESP32, ESP8266 and SAMD device, the timestamp get from result.timestamp should be valid if
      // your device time was synched with NTP server.
      // Other devices may show invalid timestamp as the device time was not set i.e. it will show Jan 1, 1970.
      // You can call smtp.setSystemTime(xxx) to set device time manually. Where xxx is timestamp (seconds since Jan 1, 1970)
      
      ESP_MAIL_PRINTF("Message No: %d\n", i + 1);
      ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");
      ESP_MAIL_PRINTF("Date/Time: %s\n", MailClient.Time.getDateTimeString(result.timestamp, "%B %d, %Y %H:%M:%S").c_str());
      ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients.c_str());
      ESP_MAIL_PRINTF("Subject: %s\n", result.subject.c_str());
    }
    Serial.println("----------------\n");

    // You need to clear sending result as the memory usage will grow up.
    smtp.sendingResult.clear();
  }
}

View raw code

You need to insert your network credentials as well as set the sender email, SMTP Server details, recipient, and message.

How the Code Works

This code is adapted from an example provided by the library. The example is well commented so that you understand what each line of code does. Let’s just take a look at the relevant parts that you need or may need to change.

First, insert your network credentials in the following lines:

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

Insert your SMTP server settings. If you’re using a Gmail account to send the emails, these are the settings:

#define SMTP_HOST "smtp.gmail.com"
#define SMTP_PORT 465

Insert the sender email login credentials (complete email and app password you created previously).

#define AUTHOR_EMAIL "[email protected]"
#define AUTHOR_PASSWORD "YOUR_EMAIL_PASS"

Insert the recipient email:

#define RECIPIENT_EMAIL "[email protected]"

You may need to adjust the gmt_offset variable depending on your location so that the email is timestamped with the right time.

config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
config.time.gmt_offset = 3;
config.time.day_light_offset = 0;

Set the message headers in the following lines in the setup()—sender name, sender email, email subject, and the recipient name and email:

  /* Set the message headers */
  message.sender.name = F("ESP");
  message.sender.email = AUTHOR_EMAIL;
  message.subject = F("ESP Test Email");
  message.addRecipient(F("Sara"), RECIPIENT_EMAIL);

In the following lines, set the content of the message (raw text) in the textMsg variable:

//Send raw text message
String textMsg = "Hello World - 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 you want to send HTML text instead, uncomment the following lines— you should insert your HTML text in the htmlMsg variable.

/*Send HTML message*/
/*String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- 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;*/

Finally, the following lines send the message:

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

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.

ESP send email SMTP server - serial monitor

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

ESP32 SMTP Server Receive Email Test

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

ESP32 SMTP Server Send Email with Body Text format HTML

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

ESP32 SMTP Server Send Email with Body Text only format

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 you 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.

For this tutorial, the files to be sent should be saved on the ESP32 filesystem (LittleFS).

Upload files to LittleFS

To send files via email, these should be saved on the ESP32 filesystem or on a microSD card. We’ll upload a picture and a .txt file to the ESP32 LittleFS filesystem 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 image.png and text_file.txt. Alternatively, you can modify the code to import files with a different name.

We’ll be sending these files:

Send emails with attachments ESP32 ESP8266 Text file and image

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

Send email attachments folder structure filesystem organizing files

After moving the files to the data folder, you need to upload them to your board. In the Arduino IDE, press [Ctrl] + [Shift] + [P] on Windows or [⌘] + [Shift] + [P] on MacOS to open the command palette. Search for the Upload LittleFS to Pico/ESP8266/ESP32 command and click on it.

Upload LittleFS to Pico ESP8266 ESP32 Arduino IDE

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 email settings and your recipient email.

/*
  Rui Santos
  Complete project details at:
   - ESP32: https://RandomNerdTutorials.com/esp32-send-email-smtp-server-arduino-ide/
   - ESP8266: https://RandomNerdTutorials.com/esp8266-nodemcu-send-email-smtp-server-arduino/
   
  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.
  Example adapted K. Suwatchai (Mobizt): https://github.com/mobizt/ESP-Mail-Client Copyright (c) 2021 mobizt
*/

// To use send Email for Gmail to port 465 (SSL), less secure app option should be enabled. https://myaccount.google.com/lesssecureapps?pli=1

#include <Arduino.h>
#if defined(ESP32)
  #include <WiFi.h>
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

#define SMTP_HOST "smtp.gmail.com"

/** The smtp port e.g. 
 * 25  or esp_mail_smtp_port_25
 * 465 or esp_mail_smtp_port_465
 * 587 or esp_mail_smtp_port_587
*/
#define SMTP_PORT 465

/* The sign in credentials */
#define AUTHOR_EMAIL "[email protected]"
#define AUTHOR_PASSWORD "YOUR_EMAIL_APP_PASS"

/* Recipient's email*/
#define RECIPIENT_EMAIL "[email protected]"

/* The SMTP Session object used for Email sending */
SMTPSession smtp;

/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status);

void setup(){
  Serial.begin(115200);
  Serial.println();
  Serial.print("Connecting to AP");
  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();

  // Init filesystem
  ESP_MAIL_DEFAULT_FLASH_FS.begin();

  /** Enable the debug via Serial port
   * none debug or 0
   * basic debug or 1
  */
  smtp.debug(1);

  /* Set the callback function to get the sending results */
  smtp.callback(smtpCallback);

  /* Declare the Session_Config for user defined session credentials */
  Session_Config config;

  /* Set the session config */
  config.server.host_name = SMTP_HOST;
  config.server.port = SMTP_PORT;
  config.login.email = AUTHOR_EMAIL;
  config.login.password = AUTHOR_PASSWORD;
  config.login.user_domain = "mydomain.net";
  
  /*
  Set the NTP config time
  For times east of the Prime Meridian use 0-12
  For times west of the Prime Meridian add 12 to the offset.
  Ex. American/Denver GMT would be -6. 6 + 12 = 18
  See https://en.wikipedia.org/wiki/Time_zone for a list of the GMT/UTC timezone offsets
  */
  config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
  config.time.gmt_offset = 3;
  config.time.day_light_offset = 0;

  /* Declare the message class */
  SMTP_Message message;

  /* Enable the chunked data transfer with pipelining for large message if server supported */
  message.enable.chunking = true;

  /* Set the message headers */
  message.sender.name = "ESP Mail";
  message.sender.email = AUTHOR_EMAIL;

  message.subject = F("Test sending Email with attachments and inline images from Flash");
  message.addRecipient(F("Sara"), RECIPIENT_EMAIL);

  /** Two alternative content versions are sending in this example e.g. plain text and html */
  String htmlMsg = "This message contains attachments: image and text file.";
  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;

  /* The attachment data item */
  SMTP_Attachment att;

  /** Set the attachment info e.g. 
   * file name, MIME type, file path, file storage type,
   * transfer encoding and content encoding
  */
  att.descr.filename = "image.png";
  att.descr.mime = "image/png"; //binary data
  att.file.path = "/image.png";
  att.file.storage_type = esp_mail_file_storage_type_flash;
  att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

  /* Add attachment to the message */
  message.addAttachment(att);

  message.resetAttachItem(att);
  att.descr.filename = "text_file.txt";
  att.descr.mime = "text/plain";
  att.file.path = "/text_file.txt";
  att.file.storage_type = esp_mail_file_storage_type_flash;
  att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;

  /* Add attachment to the message */
  message.addAttachment(att);

  /* Connect to server with the session config */
  if (!smtp.connect(&config)){
    ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
    return;
  }

  if (!smtp.isLoggedIn()){
    Serial.println("\nNot yet logged in.");
  }
  else{
    if (smtp.isAuthenticated())
      Serial.println("\nSuccessfully logged in.");
    else
      Serial.println("\nConnected with no Auth.");
  }

  /* Start sending the Email and close the session */
  if (!MailClient.sendMail(&smtp, &message, true))
    Serial.println("Error sending Email, " + smtp.errorReason());
}

void loop(){
}

/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status){
  /* Print the current status */
  Serial.println(status.info());

  /* Print the sending result */
  if (status.success()){
    Serial.println("----------------");
    ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());
    ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());
    Serial.println("----------------\n");
    struct tm dt;

    for (size_t i = 0; i < smtp.sendingResult.size(); i++){
      /* Get the result item */
      SMTP_Result result = smtp.sendingResult.getItem(i);
      time_t ts = (time_t)result.timestamp;
      localtime_r(&ts, &dt);

      ESP_MAIL_PRINTF("Message No: %d\n", i + 1);
      ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");
      ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900, dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);
      ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients.c_str());
      ESP_MAIL_PRINTF("Subject: %s\n", result.subject.c_str());
    }
    Serial.println("----------------\n");
    
    // You need to clear sending result as the memory usage will grow up.
    smtp.sendingResult.clear();
  }
}

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 initialize the filesystem using the ESP Mail Client library method. The default filesystem set in the library for the ESP32 is LittleFS (you can change the default in the library file ESP_Mail_FS.h).

// Init filesystem
ESP_MAIL_DEFAULT_FLASH_FS.begin();

You need to create an attachment as follows:

/* The attachment data item */
SMTP_Attachment att;

Then, add the attachment details: filename, MIME type, file path, file storage type, and transfer encoding. In the following lines, we’re sending the image file.

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

Finally, add the attachment to the message:

message.addAttachment(att);

If you want to send more attachments, you need to call the following line before adding the next attachment:

message.resetAttachItem(att);

Then, enter the details of the other attachment (text file):

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

And add this attachment to the message:

message.addAttachment(att);

Finally, you just need to send the message as you did with the previous example:

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

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.

ESP Send Email Message Successfully Serial Monitor

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

Send Email with Attachments ESP32 and ESP8266

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 saved on the ESP32 filesystem (LittleFS) or on a microSD card (not covered in this tutorial).

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, 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 found this tutorial interesting.

To learn more about the ESP32, take a look at our resources:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

206 thoughts on “ESP32 Send Emails using an SMTP Server: HTML, Text, and Attachments (Arduino IDE)”

  1. Hello,
    I would like to thank you for your tutorials.
    I tried to send email with a wemos D1 mini using the code in this blog and I got the following error:
    /home/samorai/Arduino/libraries/ESP32_Mail_Client/src/ssl_client32.h:32:30: fatal error: mbedtls/platform.h: No such file or directory
    #include “mbedtls/platform.h”
    I am using the latest IDE version.
    Any idea how to solve this?
    Thanks and regards

    Reply
        • Hey whenever I try to upload the code to my ESP32 I keep getting this error and II have no idea what to do. Help!

          Arduino: 1.8.17 Hourly Build 2021/09/06 02:33 (Windows 10), Board: “Arduino Uno”

          In file included from C:\Users\huntk\Documents\Arduino\libraries\ESP_Mail_Client\src/ESP_Mail_Client.h:112:0,

          from C:\Users\huntk\Documents\Arduino\ESP32_Email_Alpha\ESP32_Email_Alpha.ino:20:

          C:\Users\huntk\Documents\Arduino\libraries\ESP_Mail_Client\src/extras/ESPTimeHelper/ESPTimeHelper.h:31:10: fatal error: vector: No such file or directory

          #include

          ^~~~~~~~

          compilation terminated.

          exit status 1

          Error compiling for board Arduino Uno.

          This report would have more information with
          “Show verbose output during compilation”
          option enabled in File -> Preferences.

          Reply
      • Howdy,

        I’ve included this file into my ESP32_Mail_Client folder and still receive the same error when compiling. Does anyone have any solutions?

        Thanks

        Reply
      • I’ve got the code in my Arduino IDE, but cannot compile. I am seeing the same error.

        When I include this folder in src > mbedtls the includes seem to work, but now I have illicited this response from the code. >…/ESP32_Mail_Client/src/ESP32_MailClient.h:37:18: fatal error: ETH.h: No such file or directory
        >#include “ETH.h”

        I’m going to keep chasing this, but I feel like I have some library mismatch or version wrong. Any insights?

        Working with an 8266 – and just realizing as I typed it out that may be the source of my trouble.

        Reply
  2. Another top class tutorial from RNT ! Kudos.

    I was looking for this exact tutorial for a long time and you guys did it. Worked first shot … both the HTML and Text version mails.

    Great. Now I can get a mail when my UPS battery needs charging or when my sump water level drops below the danger mark or …. the list is endless.

    Reply
  3. Was getting many compilation until I installed version 1.0.4 for ESP32.
    Now the first text example works, will try the rest soon,
    Thanks!

    Reply
  4. If you got this obscure error below,
    #error: architecture or board not supported
    It has to do with the
    #include “ESP32_MailClient.h”
    is calling an old SD card library,
    When I got this error, the compiler is using a very old library that doesn’t recognize ESP32. I removed all the old libraries until the compiler is using the ESP32 SD card library – see below.

    Using library SD at version 1.0.5 in folder: C:\Users\one\Documents\Arduino\hardware\esp32\arduino-esp32-master\libraries\SD

    Hope this helps!

    Reply
  5. I have been looking for exactly this! Just great you posted it.
    I have the recommended ESP32 board, but the compiler tells me: “”Error compiling for board DOIT ESP32 DEVKIT V1”. Could you please help me out? Any pointers?

    Reply
    • I think A Lee had the same issue, and … the fix. I would like to try it. How do I remove and old library? I know …. rookie question.

      Reply
        • Thank you for your quick response. In the meantime I have completely removed the entire Arduino installation and its libraries and reinstalled a clean version. It compiles! 🙂

          Reply
    • If you go to File Preference and click Show Verbose Output during compilation. Then you will see a lot of messages on the screen. After the compiler stopped, you would see this message on the screen in red.

      exit status 1
      Error compiling for board ESP32 Dev Module.

      Scroll up and see where is error comes from.

      C:\Users\One\Documents\Arduino\libraries\SD\src/utility/Sd2PinMap.h:524:2: error: #error Architecture or board not supported.

      #error Architecture or board not supported.

      ^

      Sd2PinMap.h is a file under the SD directory. My Google search found not much with this type of error. One poster said the library doesn’t suppose the lastest board. It means sense because the error is Architecture or board not supported.

      I figured – the SD library probably is “old”. I started moving it to another drive in my PC and recompile the sketch. Below is the compiler telling which library it was using to compile the sketch.

      Multiple libraries were found for “SD.h”
      Used: C:\Users\One\Documents\Arduino\libraries\SD
      Not used: C:\Users\One\Documents\Arduino\hardware\esp32\arduino-esp32-master\libraries\SD

      I moved the SD directory that it was using to another drive.

      Then it complied with no error. I scroll up the screen and saw it was using the esp32 library.
      Using library SD at version 1.0.5 in folder: C:\Users\One\Documents\Arduino\hardware\esp32\arduino-esp32-master\libraries\SD

      It works for me. Good luck!

      Reply
  6. Hello, thank you for this tutorial. I am getting the following error message. Your thoughts, please. Thanks, Mac

    Connecting to SMTP server…
    SMTP server connected, wait for response…
    Identification…
    Authentication…
    Sign in…
    Error, login password is not valid
    Error sending Email, login password is not valid

    Reply
      • I have the same issue.
        I just made the email account, so I know it’s the right PW.
        Does it have issue with the ‘#’ symbol?

        Andy

        Reply
        • Hi Andy.
          Double-check that you have access to less secure apps enable.
          Sometimes Gmail changes that option without our permission.
          Regards,
          Sara

          Reply
          • Triple checked.
            I even set up a new Outlook account to see if it was Gmail.
            I get the same error.

            Should I try another email?
            Andy

          • Hi Andy.
            Honestly, I don’t know.
            It worked fine for me using a Gmail account.
            If you change to another email provider, check that you have the right smtp settings for that email provier.
            Regards,
            Sara

    • Hello Macin,
      I get the same issue but not always. Issue does not come from my password or Id because sometimes it works ! did you find a solution to your issue ?

      Reply
    • I’ve had the same issue, though the password was correct. I’ve done the following and it now works well:
      – Enable less secure apps
      – Enable 2-Step verification
      – Then Manage your google account>Security>Sign in to Google>App password>create a new app password which can only be used in the device you choose.
      The generated password should be placed on the arduino sketch replacing your main accounts password.
      If you have several ESP32 (or other devices) you should generate an app password per device.
      Hope this helps.

      Reply
  7. Hello, First of all, thanks for this post.
    I want to send an email when my Magnetic switch is HIGH. Magnetic Switch is connected to ESP32. So in which part of the code I should add this?
    It might be a simple question but I am new in Arduino, and ESP32, so please help me.

    Reply
  8. Hello and well done for your work.
    I am new to the subject and I don’t know what “SSID” is or where to find it.
    Thank you for informing me.
    Regards

    Reply
    • Hi Jean.
      SSID is the name of your internet network (Wi-Fi).
      Usually, there’s a sticker below the router with the wi-fi name.
      Also, if you search for Wi-Fi networks with your smartphone, you’ll find its name.
      Regards,
      Sara

      Reply
  9. dear if I want to send voltage value , what I should do since smtpData.setMessage(“ALI SHAMI testing “, false); support only char . thxx in advance

    Reply
  10. Hello, thank you very much for the publications, you are great.
    I have finished your project and I receive the email without the files, this is what I see on the serial monitor:
    Connecting
    WiFi connected.

    Preparing to send email

    Connecting to SMTP server …
    SMTP server connected, wait for response …
    Identification …
    Authentication …
    Sign in …
    Sending Email header …
    Sending Email body …
    Sending attachments …
    Finish …
    Finished
    Email sent successfully
    —————-
    however in the “data” folder are your files. Sorry if it’s a silly question but I’m a newbie.😊

    Reply
    • Hi Rafa.
      Thanks for your question. Did you upload the files to the ESP32 SPIFFS?
      After moving the files to the data folder, you need to go to Tools > ESP32 Data Sketch Upload
      Regards,
      Sara

      Reply
  11. Thanks for your response and sorry for the delay. It is possible that this is the problem, I have several Arduino installations and maybe it confused me. Thank you

    Reply
  12. Dear Rui and Sara
    I thank U for your Excellent work,
    I have a liiiitle problem with the attached file: it is on the SD card and I the error is in this lines :

    MailClient.sdBegin(18, 19, 23, 5); // (SCK, MISO, MOSI, CS)
    if(!SD.begin()){
    Serial.println(“Card Mount Failed”);
    return “”;
    }

    the error is : exit status 1
    return-statement with a value, in function returning ‘void’ [-fpermissive]
    I beg your help, superplease!

    Reply
  13. Hi Rui and Sara,

    It is awesome…thank you so much. Works as expected at first try with Gmail account.
    Best regards,
    Tondium

    Reply
  14. Hi,

    when I compile the sketch send email on a ESP32 dev board, I get several compiler errors. Which library is missing?

    Here the errors:
    /Users/myName/Documents/Arduino/hardware/espressif/esp32/libraries/ESP32-Mail-Client/src/ssl_client32.cpp: In function ‘int start_ssl_client(sslclient_context32*, const char*, uint32_t, int, const char*, const char*, const char*, const char*, const char)’:
    /Users/myName/Documents/Arduino/hardware/espressif/esp32/libraries/ESP32-Mail-Client/src/ssl_client32.cpp:101:48: error: cannot call member function ‘int WiFiGenericClass::hostByName(const char
    , IPAddress&)’ without object
    if (!WiFiGenericClass::hostByName(host, srv))
    ^
    /Users/myName/Documents/Arduino/hardware/espressif/esp32/libraries/ESP32-Mail-Client/src/ssl_client32.cpp:271:85: error: ‘mbedtls_ssl_conf_psk’ was not declared in this scope
    (const unsigned char *)pskIdent, strlen(pskIdent));
    ^
    /Users/myName/Documents/Arduino/hardware/espressif/esp32/libraries/ESP32-Mail-Client/src/ESP32_MailClient.cpp: In member function ‘bool ESP32_MailClient::waitIMAPResponse(IMAPData&, uint8_t, int, int, int, std::__cxx11::string)’:
    /Users/myName/Documents/Arduino/hardware/espressif/esp32/libraries/ESP32-Mail-Client/src/ESP32_MailClient.cpp:2460:9: error: ‘transform’ is not a member of ‘std’
    std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);
    ^
    /Users/myName/Documents/Arduino/hardware/espressif/esp32/libraries/ESP32-Mail-Client/src/ESP32_MailClient.cpp:2629:13: error: ‘sort’ is not a member of ‘std’
    std::sort(imapData._msgNum.begin(), imapData._msgNum.end(), compFunc);
    ^
    /Users/myName/Documents/Arduino/hardware/espressif/esp32/libraries/ESP32-Mail-Client/src/ESP32_MailClient.cpp: In member function ‘void IMAPData::setFetchUID(const String&)’:
    /Users/myName/Documents/Arduino/hardware/espressif/esp32/libraries/ESP32-Mail-Client/src/ESP32_MailClient.cpp:3702:3: error: ‘transform’ is not a member of ‘std’
    std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::toupper);
    ^

    Reply
      • Hi Kurt.
        I’m sorry for taking so long to see your comment.
        I think you have some problem with the library.
        I suggest that you delete the library from the libraries folder and try to install it again.
        Regards,
        Sara

        Reply
  15. Love this project, easy to follow and understand. Works great until I use a battery to power the ESP32. I tried different cables,batteries, power supply with no success in sending. Nothing happens. Plugged it into a wall jack with the 5v adapter and it works fine.
    What am I missing.

    Reply
  16. hello,
    can you set this project to work that door status monitor made by you? because that project doesnt work anymore because of IFTTT upgrade….
    thanks

    Reply
    • Once again – brilliant tutorial – many thanks
      I appreciate this is old but may help others.
      Define the other recipient email addresses as Carbon Copies
      eg:
      message.addCc(RECIPIENT_CC1);
      message.addCc(RECIPIENT_CC2);

      you can also send Blind Carbon Copies
      message.addBcc(RECIPIENT_BC);

      Reply
  17. Hi Guys!
    I was trying to send a sensor value (MQ-2) by e-mail, using the Wemos Lolin Oled and your code. But all the analog input PINs go to 100%… And I don’t know why!
    Do you have some idea that is happening?
    Best,
    Ricardo

    Reply
  18. Thanks the Santos to provide a lot of good projects on this site. One of my struggles is to know what IP is assigned to a “webserver” by the wireless router if there is no “display” available to show the IP address. Below are the changes that I made to the test email sketch to make it possible.

    Modify the emailSubject as a String; add localIP as a variable

    String emailSubject;
    IPAddress localIP;

    Add the following at the end of the Setup

    Serial.print(“IP: “);Serial.println(WiFi.localIP());
    localIP = WiFi.localIP();
    emailSubject =String( localIP[0]) + “.” + String( localIP[1])+ “.” + String( localIP[2]) + “.” + String( localIP[3]);
    SMTPsendmail();

    When you receive the email from your project, the IP address is on the Subject.

    Have fun!

    Reply
    • Hello! Thanks for your input Santos and Lee, I really needed this. But I have a problem when you declare SMTPsendmail();. Does this function belong to the library? Why am I getting the error: ‘SMTPsendmail’ was not declared in this scope?

      Reply
      • Are you using the latest version of the ESP32 boards installation (Tools > Boards > Boards Manager, search for ESP32 and update to the latest version)?
        Are you using the latest version of the library?
        Are you using this code on an ESP32?
        Regards,
        Sara

        Reply
  19. Rui and Sara, I’m here from BRasil to accompany you. Congratulations!
    Which command do I use to delete the SPIFFS file after it is sent?

    Reply
    • Hi.
      You can use the following command:
      SPIFFS.remove(“/filename”);
      Replace filename with the name of the file you want to remove. You also need to include the file extension.
      Regards,
      Sara

      Reply
  20. Thanks for this awesome tutorial.
    I can generate an email when the code is placed in setup(), but if I place it anywhere else I get

    [E][ssl_client32.cpp:63] handle_error(): SSL – Memory allocation failed
    [E][ssl_client32.cpp:65] handle_error(): MbedTLS message code: -32512
    [E][WiFiClientSecureESP32.cpp:179] connect(): start_ssl_client: -32512

    Any idea why this might be happening?

    Thanks for any clues!

    Reply
    • Further info: when placed before (blocking) BLE scan function, no problem, when placed after, fails. So some resource used by BLE scan is preventing email?

      Reply
    • Hey Nancy,
      Did you ever get a resolution to this problem? I see the same issue, can’t successfully place the email sending code in “loop”. (ESP32)
      Thanks, Jim

      Reply
  21. When using with Gmail, as we know we have to enable the low security mode on the Gmail account in question.
    But there is a problem in that if you don’t often send an email using this account Google will automatically turn that function back off again after a certain period of time ( how long ? – I don’t know)
    and your account will now
    I have that working fine, but in my case I only want to send a notification email as a very sporadic event
    This means there is a good chance that Google have disabled the low security mode again and my notification email will fail to get thru

    Is there some function/command ( other than an sending a spurious email) I can send to the gmail account (say once a day/week) to keep the account awake and ensure that Google don’t change the low security mode against my wishes

    Reply
      • Yes – thats what I decided to do in the end
        That email acts as the confirmation to me that Gmail is still working
        (currently it gets sent every night @ 00:00 – possibly overkill)

        Reply
  22. Hi,
    i am trying and following al of the sketches ,
    but i keep getting :
    ‘SMTPData’ does not name a type.(just copied the code)

    can you tell me how to fix this? and why this happens

    i used the latest esp32 mail client

    thanks

    Reply
    • I had the same error, but it was because I had a brain fart. Be sure the correct board type is selected in your Arduino IDE.. In my case I had a non ESP32 Board selected in error.

      Reply
    • Hi, did you find the solution? I’m having the same problem – the correct board is selected and all the libraries should be up to date.
      thanks!

      Reply
  23. Not sure if this has been already mentioned, but it’s not a good idea to make the gmail account “less secure”. Instead, create a pecial password at “Sign in with App Passwords”.
    Best regards.

    Reply
  24. i would love to interface a gps sensor with esp32 and send a panic email and text message with the gps location everytime danger is sensed by a person holding the device. the device could be a bag with a push button

    Reply
  25. I am getting an error report: ‘ESP_MAIL_PRINTF’ was not declared in this scope

    What could be the reason for this error report?

    Reply
    • Hi.
      What’s the board that you’re using?
      MAke sure you are using the latest version of the library.
      Regards,
      Sara

      Reply
  26. I found the answer to my question: there was an old version of the ESP_Mail_Client.h in my libraries folder, which was used during compialtion. Deleting that old version solved the problem.

    Reply
  27. Thanks Sara and Rui for such a complete, clear and educational tutorial! It was just what I needed. I will definitely be checking out your other tutorials. The demo code works great on my Adafruit Feather Huzzah32 board, with Yahoo email.
    A tip for Yahoo email users: I used “smtp.mail.yahoo.com” and port 465. I received “authentication failure” messages using my normal login and password. The only solution I found was to create an “App Password” on your Yahoo account web page (Account Info -> Account Security -> look for App Password section). Use the App Password in place of your normal password, and it works great!

    Reply
  28. Hi Rui and Sara,

    Thank you for all the good and well structered information in all your tutorials. You’re the best!

    In this one, I have a particular doubt.
    I implemented this on my ESP32 and have sended emails with HTML (no attachements). Worked perfectly.
    Is it possible to insert in the “String htmlMsg” arduino variables? How should I do that?
    For example:
    String htmlMsg = ”

    Hello World!Energy consumed: INSERT HERE ARDUINO VARIABLE

    “;

    Thank you in advance!

    Reply
  29. Hey, I love your tutorials.

    I tried your code month ago and it went great.
    But now I got back to different project and it doesn’t work.
    After the message “starting socket” I always get an error message “could not get ip from host”.
    Can you please help me?

    Reply
  30. Having an ESP send an email is a feature I took one step further, most cellular phone providers allow a feature they don’t tell many people about. In most cases you will need to contact the tech support to activate it.
    It can take several minutes to receive an email, depending on the frequency your device checks for new email. Receiving a text message is usually much quicker. Did you know you can send a plain text email message to your cellular phone number and receive it as a text message?
    For an example, I have a google mail account. I have also rigged up a 433 RF receiver to an ESP32. When an RF transmitter button is pressed and identified by the ESP, it sends an email to [email protected] and within a few seconds I receive a text message on my cellular phone.

    Reply
  31. Once again – great tutorial – many thanks.
    Will you be doing another one for receiving emails?

    I want to email configuration details to my ESP32 either within the message contents or as an attached text file which I can then write to flash memory. This will be much better and easier than having to use the arduino ‘upload’ and can be done without having to use the Arduino IDE.

    Reply
  32. Dear Rui and Sara,
    Thanks very much for this tutorial. The first part, sending STMP e-mail message with my ESP32 worked perfectly which is why I was surprised at receiving the following error when trying to compile the Send Attachments tutorial. I was particularly surprised since the sketches are very similar. I performed the SPIFFS plug-in and attachment upload OK and copied over your exact code without changing any of the WiFi, or e-mail parameters as a double check and still received the errors. Error message text follows bellow:

    ESP_Email_Attachments:43: error: redefinition of ‘SMTPSession smtp’
    SMTPSession smtp;
    ^
    C:\Users____\Documents\Arduino\sketch_nov18a\sketch_nov18a.ino:42:13: note: ‘SMTPSession smtp’ previously declared here
    SMTPSession smtp;
    ^
    C:\Users____\Documents\Arduino\sketch_nov18a\ESP_Email_Attachments.ino: In function ‘void setup()’:
    ESP_Email_Attachments:48: error: redefinition of ‘void setup()’
    void setup(){
    ^
    C:\Users____\Documents\Arduino\sketch_nov18a\sketch_nov18a.ino:47:6: note: ‘void setup()’ previously defined here
    void setup(){
    ^
    C:\Users____\Documents\Arduino\sketch_nov18a\ESP_Email_Attachments.ino: In function ‘void loop()’:
    ESP_Email_Attachments:146: error: redefinition of ‘void loop()’
    void loop()
    ^
    C:\Users____\Documents\Arduino\sketch_nov18a\sketch_nov18a.ino:145:6: note: ‘void loop()’ previously defined here
    void loop() { }
    ^
    C:\Users___\Documents\Arduino\sketch_nov18a\ESP_Email_Attachments.ino: In function ‘void smtpCallback(SMTP_Status)’:
    ESP_Email_Attachments:151: error: redefinition of ‘void smtpCallback(SMTP_Status)’
    void smtpCallback(SMTP_Status status){
    ^
    C:\Users____\Documents\Arduino\sketch_nov18a\sketch_nov18a.ino:148:6: note: ‘void smtpCallback(SMTP_Status)’ previously defined here
    void smtpCallback(SMTP_Status status){
    ^
    Multiple libraries were found for “WiFi.h”
    Used: C:\Users___\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.1\libraries\WiFi
    Not used: C:\Program Files (x86)\Arduino\libraries\WiFi
    Multiple libraries were found for “SD.h”
    Used: C:\Users\loren\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.1\libraries\SD
    Not used: C:\Program Files (x86)\Arduino\libraries\SD
    exit status 1
    redefinition of ‘SMTPSession smtp’

    Reply
    • Hi.
      It seems you didn’t copy the code correctly. Can you check it again?
      I just tested that code and it is compiling just fine.
      Regards,
      Sara

      Reply
      • Sara,
        Thank you so much for your response. Yes, it works fine. Initially, I had been copying the code from the window within the tutorial. This time I copied from the “VIEW RAW CODE” option and it compiled OK. Could there be a slight difference between the two?

        Reply
        • Hi.
          No, the codes are the same.
          You must have copied something twice. I recommend always copying the code from the VIEW RAW CODE option.
          Regards,
          Sara

          Reply
  33. Hi,
    I just tried this code, which is working fine (ESP32).
    A little note : Google mail does not provide the “Less Secure App” option anymore. Instead, you must create an App password. Same for Yahoo.
    Just one question: I noticed the constant decrease of the Heap value.
    Is there a way to prevent this to happen? If you leave the system unattended for a while, one could run out of memory.
    I checked the library source code, but could not find anything related to this point.
    Thanks,
    Thierry

    Reply
    • Thanks for sharing that.
      I updated the tutorial to login with an app password.

      I’m not sure what’s the answer to your question. Maybe it is better to ask the library’s developer?

      Regards,
      Sara

      Reply
  34. Hello,
    I am French man, be indulgent with my English!

    I try to use your example with a SD card File (it run well with SPIFFS), where I logged data every minutes.
    First I initialize a SD card:
    if (!SD.begin(4))
    {
    cardOK_g= 0;
    Serial.println(“Card failed, or not present je mets cardOK Ă  0”);
    }
    ….
    Then I just modify the line
    att.file.storage_type = esp_mail_file_storage_type_flash;
    By
    att.file.storage_type = esp_mail_file_storage_type_sd;

    I got the message :Sending attachments…

    C: send attachments

    Peisey1.txt

    C: Peisey1.txt
    SD Storage is not ready.
    E: SD Storage is not ready.

    did I forgot something?

    Thank a lot

    Gilles from Paris

    Reply
    • Hi.
      I’m not sure.
      I also tried it with an SD card some time ago and wasn’t able to make it work. However, I don’t remember what was exactly my problem.
      Regards,
      Sara

      Reply
  35. OlĂĄ!

    O cĂłdigo funciona perfeitamente, porem tem alguma forma para que a notificação de alerta seja envia para trĂȘs e-mails diferentes?

    Reply
  36. Thank you so much for updating this code to add 2-step-verification. My outdoor mailbox was very quiet lately and then I found out GMAIL didn’t support unsafe devices anymore since 30 May. You guys saved me from a lot of work. Thanks again!!

    Reply
  37. Thanks for great tutorial – it works perfectly but how to use it in a real-world sense? Sorry if this is dumb question but it would be more useful to me if the recipient email address was not hard coded. I pull the recipient address out of a cloud data store for my application. Is there a way to not hard code the to_address at compile time and send to the address my app has stored in a String or Char array?

    Reply
  38. Never mind figured it out. I would paste above the following section:
    #define AUTHOR_PASSWORD “YOUR_EMAIL_PASS”

    That’s where you put the app password you generated for overlogged newbs like me.

    Reply
  39. I got the error:
    undefined reference to `smtpCallback(SMTP_Status)’
    collect2: error: ld returned 1 exit status
    How to fix this ?
    Thx

    Reply
  40. Thanks for updating this to accommodate Google’s elimination of “less secure devices”. Great tutorial. My only problem was that after creating the app password, I was getting an error due to authentication failed. I finally realized that I had to open my Google email and acknowledge that I had set up the app password. After that, it worked! You may want to add this to your instructions. Thanks again. -Tom

    Reply
  41. Hi,
    Perhaps this was already commented, but because it’s not reflected in the code, I’m mentioning it here.
    There’re typos on two lines towards the end. These are the corrections:
    // ESP_MAIL_PRINTF(“Recipient: %s\n”, result.recipients);
    // ESP_MAIL_PRINTF(“Subject: %s\n”, result.subject);
    ESP_MAIL_PRINTF(“Recipient: %s\n”, result.recipients.c_str());
    ESP_MAIL_PRINTF(“Subject: %s\n”, result.subject.c_str());

    Reply
  42. Trying this and keep getting errors.

    Connecting to SMTP server…

    C: ESP Mail Client v2.5.2
    C: Wait for NTP server time synching
    C: Connect to SMTP server
    C: Host > smtp.gmail.com
    C: Port > 465
    C: seeding the random number generator
    C: setting up the SSL/TLS structure
    ! W: Skipping SSL Verification. INSECURE!
    C: setting hostname for TLS session
    C: perform the SSL/TLS handshake
    ! E: UNKNOWN ERROR CODE (0001)
    C: cleaning SSL connection
    Error, unable to connect to server
    E: unable to connect to server

    Reply
  43. Hello,

    My ESP32 Devkit 1 (wrover module) sketch is successfully sending email using my ISP’s SMTP connection (not gmail), but it fails after two sent emails. Any further emails generate error:

    Connecting to SMTP server…

    C: Wait for NTP server time synching
    Error, unable to connect to server

    I can immediately restart my ESP32 and it can then send emails, but no more than two. That indicates that my ISP isn’t rejecting the connection due to spamming or flooding.

    I am waiting between email attempts to prevent my ESP from locking me out due to flooding or spamming protection.

    In the exact example sketch above (“CODE”) I added to send more than one email:

    delay(60000);
    Serial.println(“\nSending an email 2”); // Start sending Email and close the session
    if (!MailClient.sendMail(&smtp, &message))
    Serial.println(“Error sending Email, ” + smtp.errorReason());

    delay(60000);
    Serial.println(“\nSending an email 3”); // Start sending Email and close the session
    if (!MailClient.sendMail(&smtp, &message))
    Serial.println(“Error sending Email, ” + smtp.errorReason());

    Any ideas?
    Thanks, Jim

    Reply
  44. Also…
    I added at the end of the exact example sketch above a delay and ESP restart:

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

    Serial.println(“One minute delay before ESP restart”);
    delay(60000);
    Serial.println(“\nRestarting to send another email”);
    ESP.restart();

    So it sends an email, delays and restarts the ESP, which sends an email, delays, restarts…..

    This version reliably sends an email every minute or so, which is successfully received. This demonstrates that my ESP’s SMTP session isn’t blocking my test emails as an anti spam or anti flooding measure.

    If I send multiple emails in the sketch, one per minute, only the first two are successful, with the rest resulting in:
    C: Wait for NTP server time synching
    Error, unable to connect to server

    Is there a way to terminate the SMTP session and restart it before every sending emails?

    Thanks for any recommendations.

    Reply
    • Hi.
      Supposedly the email session is closed automatically right after sending the email…
      Try to add the following line after sending the email:

      smtp.sendingResult.clear();

      Let me know if that solves the issue.
      Regards,
      Sara

      Reply
  45. Hello, Thank you for this tutorial.I was able to send the email successfully but the image and the text files are not showing in the mail,how can I fix this please?

    Reply
  46. thanks for the wonderful example, I want to expand it to send email attachment from SD Card , can you please tell me how I can attach file from SD card?

    Reply
  47. hi Sara

    is my post deleted ? I had posted a question today on how to use this example to send attachment from SD card but I dont see it here.

    please advise

    Reply
  48. Hello Sara,

    thank you for the scripts, they are great and easy to use.
    But please fix the code like Emilio wrote on July 6, 2022.

    Regards
    Nils

    Reply
      • Maybe you should als include emilio’s idear not to make the google account insecure as this is exposed to the internet?

        Not sure if this has been already mentioned, but it’s not a good idea to make the gmail account “less secure”. Instead, create a pecial password at “Sign in with App Passwords”.
        Best regards.

        Reply
        • We recommend using an App password.
          We have a section explaining how to use an APP password: see the section “Create an App Password” in the current post.
          Regards,~
          Sara

          Reply
  49. Good evening, I have successfully loaded this project, ESP32 card but I can’t compile it I get this error, if anyone can help me. thank you
    — ecco errore compilatore —
    In file included from F:\ESP32_ESP8266_RANDOM_NERD_TUTORIALS\RuiSantos_invia_mail\RuiSantos_invia_mail.ino:20:0:
    c:\Users\paolo\Documents\Arduino\libraries\ESP-Mail-Client-master\src/ESP_Mail_Client.h:55:17: fatal error: ETH.h: No such file or directory
    compilation terminated.

    exit status 1

    Compilation error: exit status 1

    Reply
  50. Hi Sara,

    email received with no attachment .
    I uploaded the 2 files using esp32 sketch data upload and said file uploaded.
    then I uploaded the email code with no error.

    Sending attachments…

    C: Send attachments

    image.png

    C: image.png
    file does not exist or can’t access
    E: File not found.

    text_file.txt

    C: text_file.txt
    file does not exist or can’t access
    E: File not found.

    Here is the error from the serial : but email received with no attachment .

    E (4016) SPIFFS: mount failed, -10025
    SPIFFS mounted successfully
    Connecting to SMTP server…

    C: ESP Mail Client v2.6.0
    ! W: PSRAM was enabled but not detected.
    C: Wait for NTP server time synching
    ../components/esp_littlefs/src/littlefs/lfs.c:1071:error: Corrupted dir pair at {0x0, 0x1}
    E (29829) esp_littlefs: mount failed, (-84)
    E (29830) esp_littlefs: Failed to initialize LittleFS
    C: Connect to SMTP server
    C: Host > smtp.gmail.com
    C: Port > 465
    C: seeding the random number generator
    C: setting up the SSL/TLS structure
    ! W: Skipping SSL Verification. INSECURE!
    C: setting hostname for TLS session
    C: perform the SSL/TLS handshake
    C: verifying peer X.509 certificate
    C: SMTP server connected

    Reply
  51. email received with no attachment.

    am getting these error.

    SPIFFS mounted successfully
    ./components/esp_littlefs/src/littlefs/lfs.c:1229:error: Corrupted dir pair at {0x0, 0x1}
    E (28343) esp_littlefs: mount failed, (-84)
    E (28344) esp_littlefs: Failed to initialize LittleFS

    My Code :;;;;;;;;;;;;;;;;;;
    #include <Arduino.h>
    #if defined(ESP32)
    #include <esp_littlefs.h>
    #include <SPIFFS.h>
    #include <WiFi.h>
    #include <ESP_Mail_Client.h>

    #define WIFI_SSID “…..”
    #define WIFI_PASSWORD “……..”

    my question is why I am geeting esp_littlefs: mount failed ?
    do I need SD card connected to my esp32 ?

    Thanks

    Reply
  52. You CAN send emails from gmail (i’m doing it) but have to turn on ‘2-Step Verification’
    1 Open your Google Account.
    2 In the navigation panel, select Security.
    3 Under “Signing in to Google,” select 2-Step Verification. Get started.
    4 Follow the on-screen steps.

    Reply
  53. Hi,
    First of all, thanks for the tutorial.
    I tried to combine smtp and firebase real time database in the same board, and the code is not working (used the ones that are provided in this website). Does the board have any constrains or can smtp and sending data to firebase realtime database work together?

    Thanks in advance

    Reply
  54. Hi, Excellent and practical application as usual.
    Not sure if this is libray or coding issue or a (more recent) gmail issue.
    The emails send according to the serial monitor and can be seen on the gmail account sent list. – however they never arrive (or perhaps were never actually sent). I tried several recipient addresses.
    If subsequently manually forwarding them from gmail sent list they go thru.
    Any ideas???

    Thanks

    Reply
  55. Hello,
    thank you for a great tutorial, I learned a lot from it (and other tutorials on your site)! I am trying to combine this project with WifiManager and the deep sleep function with the idea to set up the wifi credentials, collect additional variables (using spiffs) via phone and then run the code and send periodic email notifications. The three projects run well in isolation and the code compiles and runs. After executing the mail sending function though, I get following error message:
    Corrupted dir pair at {0x0, 0x1}
    E (28343) esp_littlefs: mount failed, (-84)
    E (28344) esp_littlefs: Failed to initialize LittleFS

    After that, the ESP32 reboots and loses the previously stored data.

    Do you happen to have any idea what would cause that? Would you have an example of combining the WifiManager and email sending capability?
    Appreciate your help!

    Reply
      • Thank you Sara for your reply!
        I have tried that, but it does not seem to work either. There seems to be a memory conflict between WiFiManager, the Sendmail function and/or deep sleep. The code is too long to post in full here, but perhaps the below extract of the error messages in sequence can give a clue?
        Thank you.

        //Declarations used:
        #define ESP_DRD_USE_SPIFFS true
        #include
        #include <Arduino.h>
        #include <WiFi.h> // WiFi Library
        //#include <FS.h> // File System Library
        #include <SPIFFS.h> // SPI Flash System Library
        #include <WiFiManager.h> // WiFiManager Library
        #include <ArduinoJson.h> // Arduino JSON library
        #include <ESP_Mail_Client.h>
        #include “DHT.h” //library for humidity and temperature sensor
        #define JSON_CONFIG_FILE “/test_config.json” // JSON configuration file

        //The function to save data in memory==>:
        bool loadConfigFile()
        // Load existing configuration file
        {
        // Uncomment if we need to format filesystem
        //SPIFFS.format();

        // Read configuration from FS json
        Serial.println(“Mounting File System…”);

        // May need to make it begin(true) first time you are using SPIFFS
        if (SPIFFS.begin(false) || SPIFFS.begin(true))
        {
        Serial.println(“mounted file system”);
        if (SPIFFS.exists(JSON_CONFIG_FILE))
        {
        // The file exists, reading and loading
        Serial.println(“reading config file”);
        File configFile = SPIFFS.open(JSON_CONFIG_FILE, “r”);
        if (configFile)
        {
        Serial.println(“Opened configuration file”);
        StaticJsonDocument json;
        DeserializationError error = deserializeJson(json, configFile);
        serializeJsonPretty(json, Serial);
        if (!error)
        {
        Serial.println(“Parsing JSON”);

        strcpy(testString1, json["testString1"]);
        testNumber1 = json["testNumber1"].as<int>();
        testNumber2 = json["testNumber2"].as<int>();
        strcpy(testString2, json["testString2"]);
        strcpy(testString3, json["testString3"]);
        strcpy(testString4, json["testString4"]);
        testNumber3 = json["testNumber3"].as<int>();
        testNumber4 = json["testNumber4"].as<int>();
        testNumber5 = json["testNumber5"].as<int>();
        testNumber6 = json["testNumber6"].as<int>();
        strcpy(testString5, json["testString5"]);
        strcpy(testString6, json["testString6"]);

        return true;
        }
        else
        {
        // Error loading JSON data
        Serial.println("Failed to load json config");
        }
        }
        }

        }
        else
        {
        // Error mounting file system
        Serial.println(“Failed to mount FS”);
        }

        return false;
        }

        void saveConfigCallback()
        // Callback notifying us of the need to save configuration
        {
        Serial.println(“Should save config”);
        shouldSaveConfig = true;
        }

        //I get following results and errors::

        //1st iteration of the program. The send mail function works properly and uses stored data to send email, however it returns following error message 

        C: ESP Mail Client v2.5.3
        C: Wait for NTP server time synching
        ./components/esp_littlefs/src/littlefs/lfs.c:1229:error: Corrupted dir pair at {0x0, 0x1}
        E (15702) esp_littlefs: mount failed, (-84)
        E (15702) esp_littlefs: Failed to initialize LittleFS
        C: Connect to SMTP server
        //After that it goes to deep sleep. Error message after waking up from deep sleep
        Mounting File System…
        E (6029) SPIFFS: mount failed, -10025
        E (6030) SPIFFS: mount failed, -10025
        mounted file system

        //Error message after send mail activation (stored data are lost and reversed to original settings):

        C: Wait for NTP server time synching
        ./components/esp_littlefs/src/littlefs/lfs.c:1229:error: Corrupted dir pair at {0x0, 0x1}
        E (35881) esp_littlefs: mount failed, (-84)
        E (35883) esp_littlefs: Failed to initialize LittleFS

        Reply
        • The library now uses LittleFS by default instead of SPIFFS.
          You just need to replace all the “SPIFFS” in your sketch with “LittleFS”.
          We’ll update the code soon.
          Regards,.
          Sara

          Reply
          • Hello Sara
            your “ESP32-CAM: Take and Send Photos via Email using an SMTP Server” example uses SPIFFS. I noticed that picture storage can fail repeatedly (0 bytes saved) before an image is stored. I then read SPIFFS is deprecated and we’d better use LittleFS. However, by replacing SPIFFS with LittleFS (or LITTLEFS? confusione about that – multiple libraries found) I get an error on smtpData.setFileStorageType(…) which doesn’t seem to accept LittleFS.
            Now I see you saying that the library (which one?) uses LittleFS by default, not SPIFFS – and you plan to update your code.
            Can you shed some light please?
            Regards,
            Michele

          • Hi.
            The library we use to send the emails now uses LittleFS by default.
            I’m currently out of the offie now, so I can’t update the code.
            Basically, you just need to replace all words “SPIFFS” with “LittleFS” in your code.
            Let me know if that solves the problem.
            Regards,
            Sara

          • Hello Sara,
            thank you for your quick reply.
            I had tried already to replace the word “SPIFFS” by “LittleFS”, but the expression “smtpData.setFileStorageType(MailClientStorageType::LittleFS);” generates a compile error – LittleFS storage type seems unknown. So my problem is still there.
            Please note I’d prefer to use the old and deprecated ESP32_Mailclient, rather than the new ESP_Mail_Client (both by Mobitz), because the latter takes much more time to send a mail.

  56. Hello, great job! Excellent tutorial.
    Is it possible to add code to send an email again once there would be a problem with sending the email for the first time?
    Sometimes I am receiving feedback from ESP that it was not able to connect to the server.

    Reply
  57. The code is working great on ESP32 DEVKITV1 boards. Thanks for the wonderful coding. I do have one ‘issue’. On the serial monitor I get the following message with every email but the emails are sent successfully via gmail account.
    “> C: Wait for NTP server time synching”

    Reply
  58. Connecting to SMTP server…

    C: ESP Mail Client v3.1.4
    C: wait for NTP server time synching

    Error, NTP server time synching timed out

    ! E: NTP server time synching timed out

    this is display in serial monitor, what the happen? pliss
    salam sahat, thank rui and sara

    Reply
    • Hi.

      I found a similar issue here: https://github.com/mobizt/ESP-Mail-Client/issues/247
      It seems a problem with your internet connection… I’m not sure.

      Either way, can you try a different version of the library?
      I use version 2.7.0 and never had that problem.
      Go to Sketch > Libraries > Manage Libraries, search for ESP Mail Client, and try to install a different version.
      Check if that works with a different version.

      Regards,
      Sara

      Reply
  59. Something has changed and broken this tutorial.

    I was also receiving the error “! E: NTP server time synching timed out”. When I raised a ticket on Github I was advised to try the example code, I did this and it works just fine.

    Clearly, there is a key difference between the library example code and the code on this webpage, what this is I am not remotely clever enough to guess but this webpage code is now giving the error.

    I am using an ESP32 DevKitC if that matters.

    Reply
  60. Hi, I keep running into a LittleFS error with your example and the attachments don’t send with the library example.

    the error code I get from your code is:
    SPIFFS mounted successfully

    Connecting to SMTP server…

    C: ESP Mail Client v3.1.4
    C: wait for NTP server time synching
    ./components/esp_littlefs/src/littlefs/lfs.c:1229:error: Corrupted dir pair at {0x0, 0x1}
    E (16523) esp_littlefs: mount failed, (-84)
    E (16524) esp_littlefs: Failed to initialize LittleFS

    Error, NTP server time synching timed out

    ! E: NTP server time synching timed out

    the board I’m using is the TTGO T-Display

    Reply
      • Good evening Sara
        firt of all, i want to thank you for this tutorial.
        Secondly i have the same error and i tried to resolve but nothing.
        Please can you help me
        =====================Monitor output===========================

        Sending Email…

        C: send Email

        Sending message header…

        C: send message header
        < S: 250 2.1.0 OK q17-20020adfdfd1000000b002e4cd2ec5c7sm1804767wrn.86 – gsmtp
        < S: 250 2.1.5 OK q17-20020adfdfd1000000b002e4cd2ec5c7sm1804767wrn.86 – gsmtp

        Sending message body…

        C: send message body
        < S: 354 Go ahead q17-20020adfdfd1000000b002e4cd2ec5c7sm1804767wrn.86 – gsmtp

        Sending attachments…

        C: send attachments

        image.png

        C: image.png
        C: file does not exist or can’t access
        ! E: file not found.

        text_file.txt

        C: text_file.txt
        C: file does not exist or can’t access
        ! E: file not found.

        Finishing the message sending…

        C: finishing the message sending
        < S: 250 2.0.0 OK 1681410897 q17-20020adfdfd1000000b002e4cd2ec5c7sm1804767wrn.86 – gsmtp

        Closing the session…

        C: terminate the SMTP session

        Message sent successfully

        C: message sent successfully

        Message sent success: 1

        Message sent failled: 0

        Message No: 1
        Status: success
        Date/Time: 1970/1/1 0:0:14
        Recipient: [email protected]

        Subject: Test sending Email with attachments and inline images from SD card and Flash

        > C: cleaning SSL connection

        ==============Mail received================================

        This message contains attachments: image and text file.

        But nothing as attachment

        Help !!!!!

        Reply
        • Hi.

          I’m getting the same issue.
          The spiffs has been uploaded and the file names match, yet it still says that the file cannot be found.

          Reply
      • Hi, sorry for the late reply.

        I have it working and sending emails now except I don’t have any attachments coming through, I have removed the image attachment and kept the .txt.
        the file name is exactly the same as the example, and the data is uploaded.
        the issue is the same with the same monitor output as Dore Pascal’s on this reply thread

        Reply
        • Hi.
          We’ve just updated the tutorial.
          Follow all the steps again and everything should work.
          We update the code and the instructions to upload files to the ESP32 filesystem (we now use LittleFS).
          Everything should be working now.
          Let me know if you can make it work.
          Regards,
          Sara

          Reply
  61. Thanks for your tutorial.
    but, i have a problem with the attached file my code is:
    Attachment Att_SMTP;
    att.descr.filename = FileName.c_str();
    att.descr.mime = “text/plain”;
    att.file.path = FileName.c_str();
    att.file.storage_type = esp_mail_file_storage_type_sd;
    att.descr.transfer_encoding=Content_Transfer_Encoding::enc_base64;
    message.addAttachment(att);

    the result is:
    /20230414.txt

    C:/20230414.txt
    SD storage is not ready.
    E: SD storage is not ready.

    so I receive the email without an attached file (normal given the result)
    In the code I can list the directory and I can list this file.

    Do you have an idea

    Reply
    • Hi.
      That’s some problem with the microSD card.
      Double-check that the SD card is properly inserted.

      Regards,
      Sara

      Reply
      • Yes my microSD card is corectly inserted.
        During my program, I can list and read all files.
        I tryed whith a litle file (75 bytes) same thing….
        Is there a specific driver for manged the microSD card adapter?

        Reply
          • Hi, this is the version of my job:
            |– ESP Mail Client @ 2.7.6
            | |– SPI @ 2.0.0
            | |– WiFi @ 2.0.0
            | |– Ethernet @ 2.0.0
            | | |– WiFi @ 2.0.0
            | |– LittleFS @ 2.0.0
            | | |– FS @ 2.0.0
            | |– SD @ 2.0.0
            | | |– FS @ 2.0.0
            | | |– SPI @ 2.0.0
            | |– SD_MMC @ 2.0.0
            | | |– FS @ 2.0.0
            | |– SPIFFS @ 2.0.0
            | | |– FS @ 2.0.0
            | |– FS @ 2.0.0
            | |– WiFiClientSecure @ 2.0.0
            | | |– WiFi @ 2.0.0
            |– WiFi @ 2.0.0
            Maybe it is a probleme of my SD shield : CATALEX MicroSD card Adapter V1.0 11/01/2013 or ESP32 shield.
            Thank you for your help

          • Hi agian.
            Have you tried a sample sketch for your microSD card to make sure everything is working properly?
            Regards,
            Sara

  62. Hello Sara
    I have the same error and I tried to resolve but nothing.
    Please can you help me
    =====================Monitor output===========================

    SPIFFS mounted successfully

    Connecting to SMTP server…

    C: ESP Mail Client v3.1.7
    C: wait for NTP server time synching
    ./components/esp_littlefs/src/littlefs/lfs.c:1229:error: Corrupted dir pair at {0x0, 0x1}
    E (11451) esp_littlefs: mount failed, (-84)
    E (11451) esp_littlefs: Failed to initialize LittleFS

    Error, NTP server time synching timed out

    ! E: NTP server time synching timed out

    C: connecting to SMTP server
    C: Host > smtp.gmail.com
    C: Port > 465

    C: SSL/TLS negotiation
    C: seeding the random number generator
    C: setting up the SSL/TLS structure
    ! W: Skipping SSL Verification. INSECURE!
    C: setting hostname for TLS session
    C: perform the SSL/TLS handshake
    C: verifying peer X.509 certificate

    SMTP server connected

    C: SMTP server connected, wait for greeting…
    < S: 220 smtp.gmail.com ESMTP u8-20020adfeb48000000b003062b2c5255sm515369wrn.40 – gsmtp

    Sending greeting response…

    C: send SMTP command, HELO
    < S: 250-smtp.gmail.com at your service, [196.220.191.53]
    < S: 250-SIZE 35882577
    < S: 250-8BITMIME
    < S: 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
    < S: 250-ENHANCEDSTATUSCODES
    < S: 250-PIPELINING
    < S: 250-CHUNKING
    < S: 250 SMTPUTF8

    Logging in…

    C: send SMTP command, AUTH PLAIN
    C: [email protected]
    C: ****************
    < S: 235 2.7.0 Accepted

    Sending Email…

    C: send Email

    Sending message header…

    C: send message header
    < S: 250 2.1.0 OK u8-20020adfeb48000000b003062b2c5255sm515369wrn.40 – gsmtp
    < S: 250 2.1.5 OK u8-20020adfeb48000000b003062b2c5255sm515369wrn.40 – gsmtp

    Sending message body…

    C: send message body
    < S: 354 Go ahead u8-20020adfeb48000000b003062b2c5255sm515369wrn.40 – gsmtp

    Sending attachments…

    C: send attachments

    text_file.txt

    C: text_file.txt
    C: file does not exist or can’t access
    ! E: file not found.

    Finishing the message sending…

    C: finishing the message sending
    < S: 250 2.0.0 OK 1686205634 u8-20020adfeb48000000b003062b2c5255sm515369wrn.40 – gsmtp

    Closing the session…

    C: terminate the SMTP session

    Message sent successfully

    C: message sent successfully

    Message sent success: 1

    Message sent failled: 0

    Message No: 1
    Status: success
    Date/Time: 1970/1/1 0:0:20
    Recipient: [email protected]

    Subject: Test sending Email with attachments and inline images from Flash

    C: cleaning SSL connection

    This is the serial monitor output right after the Ip address is displayed.

    This message contains the text file, I took out the image and its associated code.
    The only thing I can see is that the example cannot see the file.
    But the email doesn’t come with the attachment.

    Reply
    • Hi.
      We’ve just updated the tutorial.
      Follow all the steps again and everything should work.
      We update the code and the instructions to upload files to the ESP32 filesystem (we now use LittleFS).
      Everything should be working now.
      Let me know if you can make it work.
      Regards,
      Sara

      Reply
  63. Hello Team Santos,

    I have added email to existing project on an ESP32 Devkit V1, using Arduino 2.2.0 and with updated libraries. My email addition is based on RandomNerdTutorials.com/esp32-send-email-smtp-server-arduino-ide/

    The email works relatively well, except the email code is doing something with Little FS, which is stepping on my previously implemented SPIFFS storage. My SPIFFS operations work until the ESP sends an email, then the SPIFFS file system is corrupted.

    I intentionally left out from my code:
    // Init filesystem
    ESP_MAIL_DEFAULT_FLASH_FS.begin();

    and the email code produces this error message:
    E (22464) esp_littlefs: mount failed, (-84)
    E (22468) esp_littlefs: Failed to initialize LittleFS

    Other than that, the ESP mail client is working fine.

    It is possible to use the ESP_Mail_Client library without it using littleFS? I’m not sure why an email client needs to create a file system, and I’d rather it didn’t.

    I realize SPIFFS may be outdated, but my goal is to add to an existing ESP32 application that works well without ripping up the application to change the working file system.

    Thanks, Jim

    Reply
    • Hi.
      The ESPMailClient library seems to use LittleFS in the background.
      You can easily change your ESP32 code to use LittleFS by simply changing the word “SPIFFS” with the word “LittleFS” in your code.
      To upload files to LittleFS using the plugin, we’ve recently created a tutorial showing how to do that: https://randomnerdtutorials.com/esp32-littlefs-arduino-ide/

      If you want to change the ESPMailClient library to use SPIFFS as default. Go to the Library files > src > ESP_Mail_FS.h and uncomment the desired line to use SPIFFS.

      I hope this helps.

      Regards,
      Sara

      Reply
  64. I get the following smtp.errorReason every other time but in the same bootup.
    “the Session_Config object was not assigned”
    So if I boot my ESP32 the first email is always send. The next gets the error and the next after that gets send and so on. Not exacly every other but something like that. Anybody seen that?

    Reply
  65. Hello, I’m getting this as the error message. Please what might be the solution to this.

    Sending greeting response…

    C: send SMTP command, EHLO
    < S: 250-smtp.gmail.com at your service, [41.190.3.43]
    < S: 250-SIZE 35882577
    < S: 250-8BITMIME
    < S: 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
    < S: 250-ENHANCEDSTATUSCODES
    < S: 250-PIPELINING
    < S: 250-CHUNKING
    < S: 250 SMTPUTF8

    Logging in…

    C: send SMTP command, AUTH PLAIN
    C: [email protected]
    C: ****************
    < S: 534-5.7.9 Application-specific password required. Learn more at
    < S: 534 5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor p6-20020a05600c358600b0040a45fffd27sm10438240wmq.10 – gsmtp

    Error, authentication failed

    ! E: authentication failed
    Connection error, Status Code: 534, Error Code: -105, Reason: authentication failed

    Reply
  66. Hello Sarah, I am very happy that you have provided the code to send the email, however, I have a question about how to make the email send itself, when the given temperature is reached and only once. I am trying to do this and constantly below the set value the email sends cyclically all the time

    Krystian

    Reply
  67. Hello,
    many thanks for your fantastc tutorials.
    I also have a problem with the messge “file does not exist or can’t access” in ESP_Mail_Client.
    ESP8266 + LittleFS works well
    ESP8266 + SD works well
    ESP32 + SD works well
    ESP32 + FFat reports the error message
    I’m using ESP_Mail_Client v. 2.8.0 (v. 3.x.x seem not to work) and I have changed the ESP_Mail_FS.h to:
    .
    .
    #if defined(ESP8266)
    #include <LittleFS.h>
    #define ESP_MAIL_DEFAULT_FLASH_FS LittleFS

    #elif defined(ESP32)
    #include <FFat.h>
    #define ESP_MAIL_DEFAULT_FLASH_FS FFat

    #else
    #include <SPIFFS.h>
    #define ESP_MAIL_DEFAULT_FLASH_FS SPIFFS

    #endif
    ,
    ,
    What can I do?

    Reply
    • The Gmail App Password instructions supplied on this web page work correctly. Gmail assigns you the App Password, then you add it into this ino in the “#define AUTHOR_PASSWORD” line
      (I made a lone post but forgot to say it was a “reply” to this message)

      Reply
  68. The Gmail App Password instructions supplied on this web page work correctly. Gmail assigns you the App Password, then you add it into this ino in the “#define AUTHOR_PASSWORD” line

    Reply
  69. Hi!
    Thanks for the nice tutorial. Using “Send an Email with HTML or Raw Text with ESP32 (Arduino IDE)” – worked like a charm. But I’m a bit confused, it sends the message just one and I need to send a message everytime a certain event happens.
    Could you please show in a second example which parts of the code has to be in the void loop(){}. I assume that things like starting a session and then ending it everytime and similar stuff is needed.
    I couldn’t find such code after some searching – maybe publishing such code could really be helpful to many makers.

    Reply
  70. This is a great tutorial, and I have my ESP32 sending emails properly.

    I am a casual Arduino IDE coder with no formal background so the answer to my question might be very obvious and simple … please bear with me! I am trying to understand how the code works.

    My question is why the lines that send the email (per above and in Git Hub) start with an if statement. How does that cause MailClient.sendMail to execute and send the message? I do not see MailClient.sendMail anywhere else in the code.

    if (!MailClient.sendMail(&smtp, &message))
    ESP_MAIL_PRINTF(“Error, Status Code: %d, Error Code: %d, Reason: %s”, smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());

    Reply
  71. I have uploaded the sketch into my esp32 and it sends the email once as advertised. I want my sketch to be able to request the email to be sent whenever input conditions indicate an issue without having to reset the controller.. I don’t see the proper place in code to request the re-send the email and I don’t see it in the comments of the ESP MAIL CLIENT library examples.

    My sketch is similar to your THERMOSTAT WEB SERVER except that uses the deprecated library ESP32 MAIL CLIENT, not the updated ESP MAIL CLIENT library. Any pointing in the proper direction will be appreciated.

    Reply
  72. Hi,

    Compilation Error: ‘SMTPData’ does not name a type

    can you tell me how to fix this? and why this happens?

    i used de ESP_Mail_Cient.h version : 3.4.19 (not ESP32_MailClient.h)

    thanks

    Reply
  73. Hello, another great tutorial. Thank you so much.
    I was wondering how can I change the code above to do the following: I have 2 push buttons (or more), when I press the one of them an email containing a custom message should be sent like “Button 1 pressed” etc. and the same with the other buttons.
    Also is it possible if the email fail to transmited, the ESP32 to try again and again until it succeded ?
    Than you very much.

    Reply
  74. mail can be sent using wifi only but can not sent with ethernet ,even though ping is ok with ethernet , i tried with esp32 and w5500 ethernet module , mail can not
    be sent , smtp connecting fail , anyone can guide how to send email using ethernet
    Thanks

    Reply

Leave a Reply to Sara Santos Cancel reply

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.