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)

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) 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. This library is not available to install through the Arduino IDE Library Manager. Follow the next steps to install the library:

  1. Click here to download ESP-Mail-Client library .zip folder.
  2. In your Arduino IDE, go to Sketch > Include Library > Add .ZIP Library.
  3. Select the .zip file you’ve just downloaded.

Then, if you go to File > Examples > ESP-Mail-Client, you’ll find several examples that you can try. You can also access the examples in the library GitHub page—here.

If you’re using the ESP32 with VS Code + PlatformIO, you should copy the following to your platformio.ini file to include the library.

lib_deps = mobizt/ESP Mail Client @ ^1.3.0

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

Allow less secure apps

Allow less secure apps to get access to this new Gmail account, so that you’re able to send emails. You can open this link to go to that menu.

Gmail Allow Less Secure Apps to Send Email with ESP32

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
*/

//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"
#define SMTP_PORT 465

/* The sign in credentials */
#define AUTHOR_EMAIL "[email protected]"
#define AUTHOR_PASSWORD "YOUR_EMAIL_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();

  /** 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 data */
  ESP_Mail_Session session;

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

  /* Declare the message class */
  SMTP_Message message;

  /* Set the message headers */
  message.sender.name = "ESP";
  message.sender.email = AUTHOR_EMAIL;
  message.subject = "ESP Test Email";
  message.addRecipient("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;*/

  /* Set the custom message header */
  //message.addHeader("Message-ID: <[email protected]>");

  /* Connect to server with the session config */
  if (!smtp.connect(&session))
    return;

  /* Start sending Email and close the session */
  if (!MailClient.sendMail(&smtp, &message))
    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);
      ESP_MAIL_PRINTF("Subject: %s\n", result.subject);
    }
    Serial.println("----------------\n");
  }
}

View raw code

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

How the Code Works

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 sign in credentials (complete email and password)

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

Insert the recipient email:

#define RECIPIENT_EMAIL "[email protected]"

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 = "ESP";
message.sender.email = AUTHOR_EMAIL;
message.subject = "ESP Test Email";
message.addRecipient("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 Message Successfully 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 how the message looks like:

ESP32 SMTP Server Send Email with Body Text format HTML

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

ESP32 SMTP Server Send Email with Body Text only 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 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 (SPIFFS).

Upload files to SPIFFS

To send files via email, these should be saved on the ESP32 filesystem (SPIFFS). We’ll upload a picture and a .txt file to the ESP32 SPIFFS using the ESP32 Filesystem Uploader plugin for Arduino IDE. Follow the next tutorial to install the plugin if you don’t have it installed yet:

Create a new Arduino sketch and save it. Go to Sketch > Show Sketch folder. Inside the Arduino sketch folder, create a folder called data. Move a .jpg file and .txt file to your data folder.

Alternatively, you can click here to download the project folder.

Note: with the default code, your files must be named 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, in your Arduino IDE, go to Tools ESP32 Sketch Data Upload and wait for the files to be uploaded.

ESP32 Sketch Data Upload Arduino IDE SPIFFS FS Filesystem

You should get a success message on the debugging window. If the files were successfully uploaded, move on to the next section.

SPIFFS image done uploading success message

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/
   
  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
// The file systems for flash and sd memory can be changed in ESP_Mail_FS.h.

#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 log in credentials */
#define AUTHOR_EMAIL "[email protected]"
#define AUTHOR_PASSWORD "YOUR_EMAIL_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();

  if (!SPIFFS.begin(true)) {
    Serial.println("An error has occurred while mounting SPIFFS");
  }
  else{
    Serial.println("SPIFFS mounted successfully");
  }

  /** 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 data */
  ESP_Mail_Session session;

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

  /* 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 = "Test sending Email with attachments and inline images from SD card and Flash";
  message.addRecipient("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(&session))
    return;

  /* 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);
      ESP_MAIL_PRINTF("Subject: %s\n", result.subject);
    }
    Serial.println("----------------\n");
  }
}

View raw code

How the code works

This code is very similar to the previous one, so we’ll just take a look at the relevant parts to send attachments.

In the setup(), you need to initialize SPIFFS:

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

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 save on the ESP32 filesystem (SPIFFS) 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 find this tutorial interesting.

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

Thanks for reading.



Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

99 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
  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
  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
  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

Leave a Reply to kurt 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.