ESP32 Send Simple email

I have been investigating sending a simple email from ESP32 PICO D4 to be controlled by a pin going HIGH or LOW as a switch opens and closes. I have looked at the examples in the libraries and I can get some of them to send email just as it powers up but cannot see what parts of the sketch I would need to put in a function that would activate as the switch opens/closes. OR is it just meant for the external switch to switch on/off power to the ESP. and so send email as it is switched on.
one I have looked at is......
ESP32: ESP32 Send Emails using SMTP Server: HTML, Text, Attachments (Arduino IDE) | Random Nerd Tutorials

Example adapted from: GitHub - mobizt/ESP-Mail-Client: The comprehensive Arduino Email Client Library to send and read Email for Arduino devices. The library also supports other network shields or modules e.g., Wi-Fi, Ethernet, and GSM/4G modules.

this works at switch on or if enable button is pressed.......

There is another from RandonNerds that monitors temperature but I cannot get it to compile ...... it seems to not like or find EPS32_Mail_Client.h and says no such file or directory ...... yet the send-email-smtp sketch finds it OK...

You didn't post the code that somewhat works for your hardware, so in text I advise:

  1. Move most of the working email-sending code out of setup() and into it's own function.

  2. modify your loop() function to work like the StateChangeDetection or Debounce built-in example. (This ensures you get one action per button press.)

  3. call the new email-sending function from the part of the code that acts on the button press.

Thanks for the reply. This is the sketch I have been trying etc..... What is now in loop was orig in setup...... I have tried putting the most of it in loop and it stops/ starts resending as I switch the input pin... OK.., but don't get reliable sending, probably get one send at start after upload then it stops at showing the port number 465. If press enable/reset
button on board it will start from start again and either send or timeout at the line reading the time stamp. I don't have the wifi connect in the loop, ??? don't know if needed to disconnect and reconnect each 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 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>

bool ValInPin = 0;
int InPin = 13;

#define WIFI_SSID "xxxxxx"
#define WIFI_PASSWORD "xxxxxxx"

/** 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 "xxxxxx.xxxx.com"
#define SMTP_PORT 465

/* The sign in credentials */
#define AUTHOR_EMAIL "xxxxx@xxxxxxx.com"
#define AUTHOR_PASSWORD "xxxxxxxpass"

/* Recipient's email*/
#define RECIPIENT_EMAIL "xxxxx.xxxxx.com"

/* 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(){

  pinMode(InPin, INPUT);

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

void loop(){

  ValInPin = digitalRead(InPin);
 if (ValInPin == 1) {

  /*  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 = 1;
  config.time.day_light_offset = 1;

  /* Declare the message class */
  SMTP_Message message;

  /* Set the message headers */
  message.sender.name = F("ThexxxxMan");
  message.sender.email = AUTHOR_EMAIL;
  message.subject = F("Mesg from Thexxxxman");
  message.addRecipient(F("TheyyyyMan"), 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 = "- Do it Now - !! - Sent from Thexxxxman";
  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());
 }   // end if InPin
}    // end 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();
  }
}

Is InPin pulled up (or what) ?

InPin is pin 13 and has a 1k resistor to ground. And I have a 220 ohm resistor on the 3.3 volt pin, and a jumper between the end of the 220 ohm and pin 13.
So when jumper is off...... pin 13 is at Zero volts ..... and when jumper is on ..... pin 13 is at 2.73 volts according to my meter.

I think problem is related to delays in contacting NTP time server.....and it timing out.
I have now put the WIFI connection as well in the loop and all runs better. will test more tomorrow

I have updated code changing the logic of the InPin to have normal closed contact and open on alarm and added an LED to let me know if email is sending and sent..??
It works better now but still not reliable if starting up from power fail or even pressing the enable/reset on the board... If it works after startup it works very well but if it does not work after startup then seems it starts again after random startups..??
The problem is generally shown when watching the serial port on IDE and it pauses on "Reading time from NTP" with alot of dots being output..... generally in this case it will time out and not send email. after several powerups again it will probably work again OK... I attach a file of the logs from the arduino ide serial port.

ESP32email log.txt (9.1 KB)

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

bool ValInPin = 0;
int InPin = 13;
int ledPin = 2;

#define WIFI_SSID "xxxxxxxxxx"
#define WIFI_PASSWORD "xxxxxxxxxx"

/** 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 "xxxxxxx.om"
#define SMTP_PORT 465

/* The sign in credentials */
#define AUTHOR_EMAIL "xxxxxxxxxxx.com"
#define AUTHOR_PASSWORD "xxxxxxxxxxxrs"

/* Recipient's email*/
#define RECIPIENT_EMAIL "xxxxxxxxxxxxxxx.com"

/* 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(){

  pinMode(InPin, INPUT);
  pinMode(ledPin, OUTPUT);

  Serial.begin(115200);
  Serial.println();
  
}

void loop(){

  ValInPin = digitalRead(InPin);
 if (ValInPin == 0) {

  /* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status);
 
digitalWrite(ledPin, HIGH);
//wifi bit
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();
//wifi bit end

  /*  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 = 1;
  config.time.day_light_offset = 1;

  /* Declare the message class */
  SMTP_Message message;

  /* Set the message headers */
  message.sender.name = F("ThexxxxxxxxxMan");
  message.sender.email = AUTHOR_EMAIL;
  message.subject = F("Mesg from Thexxxxxxxxxman");
  message.addRecipient(F("TheyyyyyyyyyMan"), 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 = "- Don't Panic - Just Jump Now - !! - Sent from Thexxxxxxxxxxan's xxxxxxxxxxet";
  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());
 }   // end if inpin
}    // end loop xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

/* Callback function to get the Email sending status */
     //   xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx what actually calls this function...??? xxxxxxxxxxxxxxxxxxxxxxx
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");

digitalWrite(ledPin, LOW);     //      xxxxxxxxxxxxxxxxxx where is best place to put this to indicate locally that email is sent

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

  }
}

................................

I have looked at several other examples as well and seems to be problem of logging into NTP after powerup and sending first email. It either does not send or sends with a wrong time displayed in the serial monitor...this in itself is not a problem as that time is not included in the email....the time of the email is displayed as received in the inbox of the receipant.
Ihave looked at the RandomNerds Get Time... it has a different procedure and as it is works quite well but I need to modify it for my project...so will keep trying
ESP32 NTP Client-Server: Get Date and Time (Arduino IDE) | Random Nerd Tutorials

xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
this below is serial monitor of first email after power on with wrong time..hour is wrong.??

SMTP server connected

Sending greeting response...

Logging in...

Successfully logged in.

Sending Email...

Sending message header...

Sending message body...

Finishing the message sending...

Closing the session...

Message sent successfully


Message sent success: 1

Message sent failed: 0


Message No: 1

Status: success

Date/Time: June 28, 2024 55:16:42

Recipient: xxxxxxxx@.commmm

Subject: Mesg from TheGman


I have took bits of several examples an put while loop on the wifi and ntp time and email. It now connects reliably although it makes 2 or 3 attempts in the loops each time if sitting for a while. It doesent seem to keep the time even powered continuously, works best if new wifi re-connect and time is done before each email. ????? Why is that..?? I am using a ESP32 PICO D4 ...... The sketch taks about 91% of memory......is there any way of saving space.... as it has flash memory.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-date-time-ntp-client-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.
//......... now modified to make as simple as possible..??????
//............ mixture of RandomNerds Wifi, NTP time, Email, button control examples

*/

#include <Arduino.h>
#include <WiFi.h>
#include <time.h>
#include <ESP_Mail_Client.h>

const char* ssid     = "xxxxxxxxxxX";
const char* password = "xxxxxxxxxxxxxxxh";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 0;
const int   daylightOffset_sec = 3600;
struct tm timeinfo;  // made global

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

bool ValInPin = 0;
int InPin = 13;
int ledPin = 2;

/** 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 "xxxxxxxxxxxxxxxx.com"
#define SMTP_PORT 465

/* The sign in credentials */
#define AUTHOR_EMAIL "xxxxxxxxxxxxxxx.com"
#define AUTHOR_PASSWORD "xxxxxxxxxx"

/* Recipient's email*/
#define RECIPIENT_EMAIL "xxxyyyyyyyyyyyyyyyxxl.com"

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

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

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

void setup(){
 
  pinMode(InPin, INPUT);
  pinMode(ledPin, OUTPUT);

  Serial.begin(115200);
  Serial.println();
}

void loop(){

  ValInPin = digitalRead(InPin);
 if (ValInPin == 0) {

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

// Connect to Wi-Fi and get ntp time......start do ....while loop
  do{
  Serial.println("...");
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.print("w");    // print w for each try wifi
  }
  Serial.println("..");
  Serial.println("WiFi connected.");
  
  // Init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
   delay(300);
  Serial.print("t");        // print t for each try of get time
   } while (!getLocalTime(&timeinfo));      // keep trying until get time...........
  Serial.println(". . .");
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");   // print date and time all one line
   // connect to Wifi and get ntp time ....... end

  /*  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(0);

  /* 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 = "";
   
  /* Declare the message class */
  SMTP_Message message;

  /* Set the message headers */
  message.sender.name = F("ThexxxxxxxxxxMan");
  message.sender.email = AUTHOR_EMAIL;
  message.subject = F("Mesg from Thexxxxxxxxxxxman");
  message.addRecipient(F("TheyyyyyyyyyMan"), RECIPIENT_EMAIL);
    
  /*Send HTML message*/
  String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Alarm xxxx 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 = "- Don't Panic - Just Jump Now - !! - Sent from ThexxxxxxxxMan's Gadget";
  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());
 }   // end .........if inpin low
}    // end ...... loop xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

/* 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);
      
    }
    Serial.println("----------------\n");

     digitalWrite(ledPin, LOW);

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

  }
}