Refactor sendmail

This commit is contained in:
Theo Arends 2022-06-21 16:53:58 +02:00
parent 1747348558
commit ffcf90bdfe
67 changed files with 25564 additions and 25528 deletions

View File

@ -1,12 +1,12 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: ["https://www.paypal.me/mobizt"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: ["https://www.paypal.me/mobizt"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

View File

@ -1,17 +1,17 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 20
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 5
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
# Label to use when marking an issue as stale
staleLabel: wontfix
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 20
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 5
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
# Label to use when marking an issue as stale
staleLabel: wontfix
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

@ -1,21 +1,21 @@
MIT License
Copyright (c) 2021 mobizt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
MIT License
Copyright (c) 2021 mobizt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

View File

View File

@ -1,147 +1,147 @@
/**
* This example showed how to copy messages from the opened mailbox folder to other folder.
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* Define the MessageList class to add the message to copy */
MessageList toCopy;
/* Add message uid to copy to the list */
toCopy.add(3);
toCopy.add(4);
//imap.createFolder("test");
/* Copy all messages in the list to the folder "test" */
if (imap.deleteMessages(&toCopy, "test"))
Serial.println("Messages copied");
/* Delete all messages in the list from the opened folder (move to trash) */
//imap.deleteMessages(&toCopy);
//imap.deleteolder("test");
}
void loop()
{
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
/**
* This example showed how to copy messages from the opened mailbox folder to other folder.
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* Define the MessageList class to add the message to copy */
MessageList toCopy;
/* Add message uid to copy to the list */
toCopy.add(3);
toCopy.add(4);
//imap.createFolder("test");
/* Copy all messages in the list to the folder "test" */
if (imap.deleteMessages(&toCopy, "test"))
Serial.println("Messages copied");
/* Delete all messages in the list from the opened folder (move to trash) */
//imap.deleteMessages(&toCopy);
//imap.deleteolder("test");
}
void loop()
{
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}

View File

@ -1,142 +1,142 @@
/**
* This example showed how to delete messages from the opened mailbox folder.
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* Define the MessageList class to add the message to delete */
MessageList toDelete;
/* Add message uid to delete to the list */
toDelete.add(10);
toDelete.add(12);
/* Delete all messages in the list (move to trash) */
if(imap.deleteMessages(&toDelete))
Serial.println("Messages deeted");
/* Delete all messages permanently by assign the second param to true*/
//imap.deleteMessages(&toDelete, true);
}
void loop()
{
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
/**
* This example showed how to delete messages from the opened mailbox folder.
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* Define the MessageList class to add the message to delete */
MessageList toDelete;
/* Add message uid to delete to the list */
toDelete.add(10);
toDelete.add(12);
/* Delete all messages in the list (move to trash) */
if(imap.deleteMessages(&toDelete))
Serial.println("Messages deeted");
/* Delete all messages permanently by assign the second param to true*/
//imap.deleteMessages(&toDelete, true);
}
void loop()
{
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}

View File

@ -1,370 +1,370 @@
/**
* This example will log in with the SASL XOAUTH2 mechanisme using OAuth2.0 access token.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The user Email for OAuth2.0 access token */
#define AUTHOR_EMAIL "################"
/** The OAuth2.0 access token
* The generation, exchange and refresh of the access token are not available
* in this library.
*
* To test this using GMail, get the OAuth2.0 access token from this web site
* https://developers.google.com/oauthplayground/
*
* 1. Select the following scope (in Step 1) from Gmail API V1
* https://mail.google.com/
* https://mail.google.com/
*
* 2. Click Authorize APIs button.
* 3. Cick Exchangeauthorization code for tokens.
* 4. From the response, look at access_token from the JSON payload node.
* 5. Copy that access token and paste to the AUTHOR_ACCESS_TOKEN value.
*
* The token will be expired in 3600 seconds (1 Hr).
* The AUTHOR_EMAIL above is the Email address that you granted to access the Gmail services.
*/
#define AUTHOR_ACCESS_TOKEN "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.accessToken = AUTHOR_ACCESS_TOKEN;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Message UID to fetch or read e.g. 100 */
config.fetch.uid = "100";
/* Set seen flag*/
//config.fetch.set_seen = true;
/* Search criteria */
config.search.criteria = "";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = true;
config.download.text = true;
config.download.html = true;
config.download.attachment = true;
config.download.inlineImg = true;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
/* Read or search the Email and close the session */
MailClient.readMail(&imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
void loop()
{
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
Serial.printf("Free Heap: %d", ESP.getFreeHeap());
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}
/**
* This example will log in with the SASL XOAUTH2 mechanisme using OAuth2.0 access token.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The user Email for OAuth2.0 access token */
#define AUTHOR_EMAIL "################"
/** The OAuth2.0 access token
* The generation, exchange and refresh of the access token are not available
* in this library.
*
* To test this using GMail, get the OAuth2.0 access token from this web site
* https://developers.google.com/oauthplayground/
*
* 1. Select the following scope (in Step 1) from Gmail API V1
* https://mail.google.com/
* https://mail.google.com/
*
* 2. Click Authorize APIs button.
* 3. Cick Exchangeauthorization code for tokens.
* 4. From the response, look at access_token from the JSON payload node.
* 5. Copy that access token and paste to the AUTHOR_ACCESS_TOKEN value.
*
* The token will be expired in 3600 seconds (1 Hr).
* The AUTHOR_EMAIL above is the Email address that you granted to access the Gmail services.
*/
#define AUTHOR_ACCESS_TOKEN "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.accessToken = AUTHOR_ACCESS_TOKEN;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Message UID to fetch or read e.g. 100 */
config.fetch.uid = "100";
/* Set seen flag*/
//config.fetch.set_seen = true;
/* Search criteria */
config.search.criteria = "";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = true;
config.download.text = true;
config.download.html = true;
config.download.attachment = true;
config.download.inlineImg = true;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
/* Read or search the Email and close the session */
MailClient.readMail(&imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
void loop()
{
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
Serial.printf("Free Heap: %d", ESP.getFreeHeap());
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}

View File

@ -1,364 +1,364 @@
/**
* This example will fetch or read the Email which the known message UID
* was used for fetching.
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/* Declare the session config data */
ESP_Mail_Session session;
/** ########################################################
* Some properties of IMAP_Config and ESP_Mail_Session data
* accept the pointer to constant char i.e. const char*.
*
* You may assign a string literal to that properties like
* below example.
*
* config.storage.saved_path = String("/email_data").c_str();
*
* String folder = "INBOX";
* imap.selectFolder(folder.c_str());
*
* ###########################################################
*/
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Message UID to fetch or read e.g. 100 */
config.fetch.uid = "100";
/* Set seen flag */
//config.fetch.set_seen = true;
/* Search criteria */
config.search.criteria = "";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = true;
config.download.text = true;
config.download.html = true;
config.download.attachment = true;
config.download.inlineImg = true;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
/* Read or search the Email and close the session */
MailClient.readMail(&imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
void loop()
{
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
Serial.printf("Free Heap: %d", ESP.getFreeHeap());
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}
/**
* This example will fetch or read the Email which the known message UID
* was used for fetching.
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/* Declare the session config data */
ESP_Mail_Session session;
/** ########################################################
* Some properties of IMAP_Config and ESP_Mail_Session data
* accept the pointer to constant char i.e. const char*.
*
* You may assign a string literal to that properties like
* below example.
*
* config.storage.saved_path = String("/email_data").c_str();
*
* String folder = "INBOX";
* imap.selectFolder(folder.c_str());
*
* ###########################################################
*/
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Message UID to fetch or read e.g. 100 */
config.fetch.uid = "100";
/* Set seen flag */
//config.fetch.set_seen = true;
/* Search criteria */
config.search.criteria = "";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = true;
config.download.text = true;
config.download.html = true;
config.download.attachment = true;
config.download.inlineImg = true;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
/* Read or search the Email and close the session */
MailClient.readMail(&imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
void loop()
{
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
Serial.printf("Free Heap: %d", ESP.getFreeHeap());
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}

View File

@ -1,376 +1,376 @@
/**
* This example will repeatedly fetch or read the Email via the loop function
* using the predict next message UID as the starting count down message UID.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
unsigned long readMillis = 0;
int nextMsgUID = 0;
int msgUID = 0;
int sign = -1;
/* Declare the session config data */
ESP_Mail_Session session;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Message UID to fetch or read */
config.fetch.uid = "";
/* Search criteria */
config.search.criteria = "";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = false;
config.download.text = false;
config.download.html = false;
config.download.attachment = false;
config.download.inlineImg = false;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
}
void loop()
{
if (millis() - readMillis > 10000 || readMillis == 0)
{
readMillis = millis();
if (msgUID == 0)
sign = 1;
else if (msgUID >= nextMsgUID)
sign = -1;
msgUID += sign;
String uid = String(msgUID);
/* Message UID to fetch or read */
config.fetch.uid = uid.c_str();
/* Set seen flag */
//config.fetch.set_seen = true;
/** Read or search the Email and keep the TCP session to open
* The second parameter is for close the session.
*/
MailClient.readMail(&imap, false);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
Serial.printf("Free Heap: %d", ESP.getFreeHeap());
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
nextMsgUID = sFolder.nextUID();
msgUID = nextMsgUID;
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}
/**
* This example will repeatedly fetch or read the Email via the loop function
* using the predict next message UID as the starting count down message UID.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
unsigned long readMillis = 0;
int nextMsgUID = 0;
int msgUID = 0;
int sign = -1;
/* Declare the session config data */
ESP_Mail_Session session;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Message UID to fetch or read */
config.fetch.uid = "";
/* Search criteria */
config.search.criteria = "";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = false;
config.download.text = false;
config.download.html = false;
config.download.attachment = false;
config.download.inlineImg = false;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
}
void loop()
{
if (millis() - readMillis > 10000 || readMillis == 0)
{
readMillis = millis();
if (msgUID == 0)
sign = 1;
else if (msgUID >= nextMsgUID)
sign = -1;
msgUID += sign;
String uid = String(msgUID);
/* Message UID to fetch or read */
config.fetch.uid = uid.c_str();
/* Set seen flag */
//config.fetch.set_seen = true;
/** Read or search the Email and keep the TCP session to open
* The second parameter is for close the session.
*/
MailClient.readMail(&imap, false);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
Serial.printf("Free Heap: %d", ESP.getFreeHeap());
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
nextMsgUID = sFolder.nextUID();
msgUID = nextMsgUID;
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}

View File

@ -1,402 +1,402 @@
/**
* This example will search all Emails in the opened mailbox folder.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/* Declare the session config data */
ESP_Mail_Session session;
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/** ########################################################
* Some properties of IMAP_Config and ESP_Mail_Session data
* accept the pointer to constant char i.e. const char*.
*
* You may assign a string literal to that properties like
* below example.
*
* config.search.criteria = String("UID SEARCH ALL").c_str();
*
* String folder = "INBOX";
* imap.selectFolder(folder.c_str());
*
* ###########################################################
*/
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Message UID to fetch or read */
config.fetch.uid = "";
/** Search criteria
*
* A search key can also be a parenthesized list of one or more search keys
* (e.g., for use with the OR and NOT keys).
*
* Since IMAP protocol uses Polish notation, the search criteria which in the polish notation form can be.
*
* To search the message from "someone@email.com" with the subject "my subject" since 1 Jan 2021, your search criteria can be
* UID SEARCH (OR SUBJECT "my subject" FROM "someone@email.com") SINCE "Fri, 1 Jan 2021 21:52:25 -0800"
*
* To search the message from "mail1@domain.com" or from "mail2@domain.com", the search criteria will be
* UID SEARCH OR FROM mail1@domain.com FROM mail2@domain.com
*
* For more details on using parentheses, AND, OR and NOT search keys in search criteria.
* https://www.limilabs.com/blog/imap-search-requires-parentheses
*
*
*/
config.search.criteria = "UID SEARCH ALL";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = true;
config.download.text = true;
config.download.html = true;
config.download.attachment = true;
config.download.inlineImg = true;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
/** Read or search the Email and keep the TCP session to open
* The second parameter is for close the session.
*/
MailClient.readMail(&imap, false);
/* Clear all stored data in IMAPSession object */
imap.empty();
/** Open or select other mailbox folder
* The folder that previousely opened will be closed
*/
if (imap.selectFolder("Junk"))
{
/* {Optional] */
printSelectedMailboxInfo(imap);
/* Config to search all messages in the opened mailboax (Search mode) */
config.search.criteria = "UID SEARCH ALL"; // or "UID SEARCH NEW" for recent received messages
/* No message UID provide for fetching */
config.fetch.uid = "";
/* Search the Email and close the session */
MailClient.readMail(&imap);
}
/* Close the seeion in case the session is still open */
imap.closeSession();
/* Clear all stored data in IMAPSession object */
imap.empty();
}
void loop()
{
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}
/**
* This example will search all Emails in the opened mailbox folder.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/* Declare the session config data */
ESP_Mail_Session session;
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/** ########################################################
* Some properties of IMAP_Config and ESP_Mail_Session data
* accept the pointer to constant char i.e. const char*.
*
* You may assign a string literal to that properties like
* below example.
*
* config.search.criteria = String("UID SEARCH ALL").c_str();
*
* String folder = "INBOX";
* imap.selectFolder(folder.c_str());
*
* ###########################################################
*/
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Message UID to fetch or read */
config.fetch.uid = "";
/** Search criteria
*
* A search key can also be a parenthesized list of one or more search keys
* (e.g., for use with the OR and NOT keys).
*
* Since IMAP protocol uses Polish notation, the search criteria which in the polish notation form can be.
*
* To search the message from "someone@email.com" with the subject "my subject" since 1 Jan 2021, your search criteria can be
* UID SEARCH (OR SUBJECT "my subject" FROM "someone@email.com") SINCE "Fri, 1 Jan 2021 21:52:25 -0800"
*
* To search the message from "mail1@domain.com" or from "mail2@domain.com", the search criteria will be
* UID SEARCH OR FROM mail1@domain.com FROM mail2@domain.com
*
* For more details on using parentheses, AND, OR and NOT search keys in search criteria.
* https://www.limilabs.com/blog/imap-search-requires-parentheses
*
*
*/
config.search.criteria = "UID SEARCH ALL";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = true;
config.download.text = true;
config.download.html = true;
config.download.attachment = true;
config.download.inlineImg = true;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
/** Read or search the Email and keep the TCP session to open
* The second parameter is for close the session.
*/
MailClient.readMail(&imap, false);
/* Clear all stored data in IMAPSession object */
imap.empty();
/** Open or select other mailbox folder
* The folder that previousely opened will be closed
*/
if (imap.selectFolder("Junk"))
{
/* {Optional] */
printSelectedMailboxInfo(imap);
/* Config to search all messages in the opened mailboax (Search mode) */
config.search.criteria = "UID SEARCH ALL"; // or "UID SEARCH NEW" for recent received messages
/* No message UID provide for fetching */
config.fetch.uid = "";
/* Search the Email and close the session */
MailClient.readMail(&imap);
}
/* Close the seeion in case the session is still open */
imap.closeSession();
/* Clear all stored data in IMAPSession object */
imap.empty();
}
void loop()
{
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}

View File

@ -1,203 +1,203 @@
/**
*This example will log in with the SASL XOAUTH2 mechanisme using OAuth2.0 access token.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
#define SMTP_HOST "################"
/** 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 25
/* The user Email for OAuth2.0 access token */
#define AUTHOR_EMAIL "################"
/** The OAuth2.0 access token
* The generation, exchange and refresh of the access token are not available
* in this library.
*
* To test this using GMail, get the OAuth2.0 access token from this web site
* https://developers.google.com/oauthplayground/
*
* You can use the ESP Signer library to generate OAuth2.0 access token
* The library is available here https://github.com/mobizt/ESP-Signer
*
* 1. Select the following scope (in Step 1) from Gmail API V1
* https://mail.google.com/
* https://mail.google.com/
*
* 2. Click Authorize APIs button.
* 3. Cick Exchangeauthorization code for tokens.
* 4. From the response, look at access_token from the JSON payload node.
* 5. Copy that access token and paste to the AUTHOR_ACCESS_TOKEN value.
*
* The token will be expired in 3600 seconds (1 Hr).
* The AUTHOR_EMAIL above is the Email address that you granted to access the Gmail services.
*/
#define AUTHOR_ACCESS_TOKEN "################"
/* 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.accessToken = AUTHOR_ACCESS_TOKEN;
session.login.user_domain = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending Email using Access token";
message.addRecipient("Admin", "####@#####_dot_com");
message.text.content = "This is simple plain text message";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;
/* Connect to server with the session config */
if (!smtp.connect(&session))
return;
/* Set the custom message header */
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
*This example will log in with the SASL XOAUTH2 mechanisme using OAuth2.0 access token.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
#define SMTP_HOST "################"
/** 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 25
/* The user Email for OAuth2.0 access token */
#define AUTHOR_EMAIL "################"
/** The OAuth2.0 access token
* The generation, exchange and refresh of the access token are not available
* in this library.
*
* To test this using GMail, get the OAuth2.0 access token from this web site
* https://developers.google.com/oauthplayground/
*
* You can use the ESP Signer library to generate OAuth2.0 access token
* The library is available here https://github.com/mobizt/ESP-Signer
*
* 1. Select the following scope (in Step 1) from Gmail API V1
* https://mail.google.com/
* https://mail.google.com/
*
* 2. Click Authorize APIs button.
* 3. Cick Exchangeauthorization code for tokens.
* 4. From the response, look at access_token from the JSON payload node.
* 5. Copy that access token and paste to the AUTHOR_ACCESS_TOKEN value.
*
* The token will be expired in 3600 seconds (1 Hr).
* The AUTHOR_EMAIL above is the Email address that you granted to access the Gmail services.
*/
#define AUTHOR_ACCESS_TOKEN "################"
/* 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.accessToken = AUTHOR_ACCESS_TOKEN;
session.login.user_domain = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending Email using Access token";
message.addRecipient("Admin", "####@#####_dot_com");
message.text.content = "This is simple plain text message";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;
/* Connect to server with the session config */
if (!smtp.connect(&session))
return;
/* Set the custom message header */
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,268 +1,268 @@
/**
* This example will send the Email with attachments and
* inline images stored in heap and flash memories.
*
* The html and text version messages will be sent.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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>
/* This is for attachment data */
#include "image.h"
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 esp_mail_smtp_port_587
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "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";
message.addRecipient("user1", "####@#####_dot_com");
message.html.content = "<span style=\"color:#ff0000;\">This message contains 3 inline images and 1 attachment file.</span><br/><br/><img src=\"firebase_logo.png\" width=\"80\" height=\"60\"> <img src=\"tree.gif\" width=\"40\" height=\"60\"> <img src=\"bird.gif\" width=\"116\" height=\"75\">";
/** The HTML text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
message.text.content = "This message contains 3 inline images and 1 attachment file.\r\nThe inline images were not shown in the plain text message.";
message.text.charSet = "utf-8";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <user1@gmail.com>");
/* The attachment data item */
SMTP_Attachment att;
/** Set the inline image info e.g.
* file name, MIME type, BLOB data, BLOB data size,
* transfer encoding (should be base64 for inline image)
*/
att.descr.filename = "firebase_logo.png";
att.descr.mime = "image/png";
att.blob.data = firebase_png;
att.blob.size = sizeof(firebase_png);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add inline image to the message */
message.addInlineImage(att);
/** Set the inline image info e.g.
* file name, MIME type, BLOB data, BLOB data size.
* The default transfer encoding is base64.
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "tree.gif";
att.descr.mime = "image/gif";
att.blob.data = tree_gif;
att.blob.size = sizeof(tree_gif);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add inline image to the message */
message.addInlineImage(att);
/** Set the inline image info e.g.
* file name, MIME type, BLOB data, BLOB data size.
* The default transfer encoding is base64.
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "bird.gif";
att.descr.mime = "image/gif";
att.blob.data = bird_gif;
att.blob.size = sizeof(bird_gif);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add inline image to the message */
message.addInlineImage(att);
/* Prepare the attachment data (from ram) */
uint8_t *a = new uint8_t[512];
int j = 0;
for (int i = 0; i < 512; i++)
{
a[i] = j;
j++;
if (j > 255)
j = 0;
}
/** Set the attachment info e.g.
* file name, MIME type, BLOB data, BLOB data size.
* The default transfer encoding is base64.
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "test.dat";
att.descr.mime = "application/octet-stream";
att.blob.data = a;
att.blob.size = 512;
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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email with attachments and
* inline images stored in heap and flash memories.
*
* The html and text version messages will be sent.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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>
/* This is for attachment data */
#include "image.h"
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 esp_mail_smtp_port_587
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "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";
message.addRecipient("user1", "####@#####_dot_com");
message.html.content = "<span style=\"color:#ff0000;\">This message contains 3 inline images and 1 attachment file.</span><br/><br/><img src=\"firebase_logo.png\" width=\"80\" height=\"60\"> <img src=\"tree.gif\" width=\"40\" height=\"60\"> <img src=\"bird.gif\" width=\"116\" height=\"75\">";
/** The HTML text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
message.text.content = "This message contains 3 inline images and 1 attachment file.\r\nThe inline images were not shown in the plain text message.";
message.text.charSet = "utf-8";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <user1@gmail.com>");
/* The attachment data item */
SMTP_Attachment att;
/** Set the inline image info e.g.
* file name, MIME type, BLOB data, BLOB data size,
* transfer encoding (should be base64 for inline image)
*/
att.descr.filename = "firebase_logo.png";
att.descr.mime = "image/png";
att.blob.data = firebase_png;
att.blob.size = sizeof(firebase_png);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add inline image to the message */
message.addInlineImage(att);
/** Set the inline image info e.g.
* file name, MIME type, BLOB data, BLOB data size.
* The default transfer encoding is base64.
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "tree.gif";
att.descr.mime = "image/gif";
att.blob.data = tree_gif;
att.blob.size = sizeof(tree_gif);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add inline image to the message */
message.addInlineImage(att);
/** Set the inline image info e.g.
* file name, MIME type, BLOB data, BLOB data size.
* The default transfer encoding is base64.
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "bird.gif";
att.descr.mime = "image/gif";
att.blob.data = bird_gif;
att.blob.size = sizeof(bird_gif);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add inline image to the message */
message.addInlineImage(att);
/* Prepare the attachment data (from ram) */
uint8_t *a = new uint8_t[512];
int j = 0;
for (int i = 0; i < 512; i++)
{
a[i] = j;
j++;
if (j > 255)
j = 0;
}
/** Set the attachment info e.g.
* file name, MIME type, BLOB data, BLOB data size.
* The default transfer encoding is base64.
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "test.dat";
att.descr.mime = "application/octet-stream";
att.blob.data = a;
att.blob.size = 512;
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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,427 +1,427 @@
/**
* This example will send the Email with attachments and
* inline images stored in flash and SD card.
*
* The html and text version messages will be sent.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 esp_mail_smtp_port_587
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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();
static uint8_t buf[512];
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
Serial.println("Mounting SD Card...");
#if defined(ESP32)
if (SD.begin()) // MailClient.sdBegin(14,2,15,13) for TTGO T8 v1.7 or 1.8
#elif defined(ESP8266)
if (SD.begin(15))
#endif
{
if (SD.exists("/orange.png"))
SD.remove("/orange.png");
if (SD.exists("/bin1.dat"))
SD.remove("/bin1.dat");
Serial.println("Preparing SD file attachments...");
const char *orangeImg = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAoUlEQVR42u3RMQ0AMAgAsCFgftHLiQpsENJaaFT+fqwRQoQgRAhChCBECEKECBGCECEIEYIQIQgRghCECEGIEIQIQYgQhCBECEKEIEQIQoQgBCFCECIEIUIQIgQhCBGCECEIEYIQIQhBiBCECEGIEIQIQQhChCBECEKEIEQIQhAiBCFCECIEIUIQghAhCBGCECEIEYIQIUKEIEQIQoQg5LoBGi/oCaOpTXoAAAAASUVORK5CYII=";
File file = SD.open("/orange.png", FILE_WRITE);
file.print(orangeImg);
file.close();
file = SD.open("/bin1.dat", FILE_WRITE);
buf[0] = 'H';
buf[1] = 'E';
buf[2] = 'A';
buf[3] = 'D';
file.write(buf, 4);
size_t i;
for (i = 0; i < 4; i++)
{
memset(buf, i + 1, 512);
file.write(buf, 512);
}
buf[0] = 'T';
buf[1] = 'A';
buf[2] = 'I';
buf[3] = 'L';
file.write(buf, 4);
file.close();
}
else
{
Serial.println("SD Card Monting Failed");
}
Serial.println("Mounting SPIFFS...");
#if defined(ESP32)
if (SPIFFS.begin(true))
#elif defined(ESP8266)
if (SPIFFS.begin())
#endif
{
//SPIFFS.format();
if (SPIFFS.exists("/green.png"))
SPIFFS.remove("/green.png");
if (SPIFFS.exists("/bin2.dat"))
SPIFFS.remove("/bin2.dat");
Serial.println("Preparing SPIFFS attachments...");
const char *greenImg = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAoUlEQVR42u3RAQ0AMAgAoJviyWxtAtNYwzmoQGT/eqwRQoQgRAhChCBECEKECBGCECEIEYIQIQgRghCECEGIEIQIQYgQhCBECEKEIEQIQoQgBCFCECIEIUIQIgQhCBGCECEIEYIQIQhBiBCECEGIEIQIQQhChCBECEKEIEQIQhAiBCFCECIEIUIQghAhCBGCECEIEYIQIUKEIEQIQoQg5LoBBaDPbQYiMoMAAAAASUVORK5CYII=";
#if defined(ESP32)
File file = SPIFFS.open("/green.png", FILE_WRITE);
#elif defined(ESP8266)
File file = SPIFFS.open("/green.png", "w");
#endif
file.print(greenImg);
file.close();
#if defined(ESP32)
file = SPIFFS.open("/bin2.dat", FILE_WRITE);
#elif defined(ESP8266)
file = SPIFFS.open("/bin2.dat", "w");
#endif
buf[0] = 'H';
buf[1] = 'E';
buf[2] = 'L';
buf[3] = 'L';
buf[4] = 'O';
file.write(buf, 5);
size_t i;
for (i = 0; i < 4; i++)
{
memset(buf, i + 1, 512);
file.write(buf, 512);
}
buf[0] = 'G';
buf[1] = 'O';
buf[2] = 'O';
buf[3] = 'D';
buf[4] = 'B';
buf[5] = 'Y';
buf[6] = 'E';
file.write(buf, 7);
file.close();
}
else
{
Serial.println("SPIFFS Monting Failed");
}
/** 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;
/** ########################################################
* Some properties of SMTPSession data and parameters pass to
* SMTP_Message class accept the pointer to constant char
* i.e. const char*.
*
* You may assign a string literal to that properties or function
* like below example.
*
* session.login.user_domain = "mydomain.net";
* session.login.user_domain = String("mydomain.net").c_str();
*
* or
*
* String doman = "mydomain.net";
* session.login.user_domain = domain.c_str();
*
* And
*
* String name = "Jack " + String("dawson");
* String email = "jack_dawson" + String(123) + "@mail.com";
*
* message.addRecipient(name.c_str(), email.c_str());
*
* message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str());
*
* or
*
* String header = "Message-ID: <abcde.fghij@gmail.com>";
* message.addHeader(header.c_str());
*
* ###########################################################
*/
/* 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("user1", "####@#####_dot_com");
/** Two alternative content versions are sending in this example e.g. plain text and html */
String htmlMsg = "<span style=\"color:#ff0000;\">This message contains 2 inline images and 2 attachment files.</span><br/><br/><img src=\"green.png\" width=\"100\" height=\"100\"> <img src=\"orange.png\" width=\"100\" height=\"100\">";
message.html.content = htmlMsg.c_str();
/** The HTML text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
message.text.content = "This message contains 2 inline images and 2 attachment files.\r\nThe inline images were not shown in the plain text message.";
message.text.charSet = "utf-8";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <user1@gmail.com>");
/* The attachment data item */
SMTP_Attachment att;
/** Set the inline image info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
att.descr.filename = "orange.png";
att.descr.mime = "image/png";
att.file.path = "/orange.png";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
att.file.storage_type = esp_mail_file_storage_type_sd;
/* Need to be base64 transfer encoding for inline image */
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The orange.png file is already base64 encoded file.
* Then set the content encoding to match the transfer encoding
* which no encoding was taken place prior to sending.
*/
att.descr.content_encoding = Content_Transfer_Encoding::enc_base64;
/* Add inline image to the message */
message.addInlineImage(att);
/** Set the attachment info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "bin1.dat";
att.descr.mime = "application/octet-stream"; //binary data
att.file.path = "/bin1.dat";
att.file.storage_type = esp_mail_file_storage_type_sd;
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add attachment to the message */
message.addAttachment(att);
/** Set the inline image info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "green.png";
att.descr.mime = "image/png";
att.file.path = "/green.png";
att.file.storage_type = esp_mail_file_storage_type_flash;
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
att.descr.content_encoding = Content_Transfer_Encoding::enc_base64;
message.addInlineImage(att);
/** Set the attachment info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "bin2.dat";
att.descr.mime = "application/octet-stream";
att.file.path = "/bin2.dat";
att.file.storage_type = esp_mail_file_storage_type_flash;
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email with attachments and
* inline images stored in flash and SD card.
*
* The html and text version messages will be sent.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 esp_mail_smtp_port_587
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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();
static uint8_t buf[512];
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
Serial.println("Mounting SD Card...");
#if defined(ESP32)
if (SD.begin()) // MailClient.sdBegin(14,2,15,13) for TTGO T8 v1.7 or 1.8
#elif defined(ESP8266)
if (SD.begin(15))
#endif
{
if (SD.exists("/orange.png"))
SD.remove("/orange.png");
if (SD.exists("/bin1.dat"))
SD.remove("/bin1.dat");
Serial.println("Preparing SD file attachments...");
const char *orangeImg = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAoUlEQVR42u3RMQ0AMAgAsCFgftHLiQpsENJaaFT+fqwRQoQgRAhChCBECEKECBGCECEIEYIQIQgRghCECEGIEIQIQYgQhCBECEKEIEQIQoQgBCFCECIEIUIQIgQhCBGCECEIEYIQIQhBiBCECEGIEIQIQQhChCBECEKEIEQIQhAiBCFCECIEIUIQghAhCBGCECEIEYIQIUKEIEQIQoQg5LoBGi/oCaOpTXoAAAAASUVORK5CYII=";
File file = SD.open("/orange.png", FILE_WRITE);
file.print(orangeImg);
file.close();
file = SD.open("/bin1.dat", FILE_WRITE);
buf[0] = 'H';
buf[1] = 'E';
buf[2] = 'A';
buf[3] = 'D';
file.write(buf, 4);
size_t i;
for (i = 0; i < 4; i++)
{
memset(buf, i + 1, 512);
file.write(buf, 512);
}
buf[0] = 'T';
buf[1] = 'A';
buf[2] = 'I';
buf[3] = 'L';
file.write(buf, 4);
file.close();
}
else
{
Serial.println("SD Card Monting Failed");
}
Serial.println("Mounting SPIFFS...");
#if defined(ESP32)
if (SPIFFS.begin(true))
#elif defined(ESP8266)
if (SPIFFS.begin())
#endif
{
//SPIFFS.format();
if (SPIFFS.exists("/green.png"))
SPIFFS.remove("/green.png");
if (SPIFFS.exists("/bin2.dat"))
SPIFFS.remove("/bin2.dat");
Serial.println("Preparing SPIFFS attachments...");
const char *greenImg = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAoUlEQVR42u3RAQ0AMAgAoJviyWxtAtNYwzmoQGT/eqwRQoQgRAhChCBECEKECBGCECEIEYIQIQgRghCECEGIEIQIQYgQhCBECEKEIEQIQoQgBCFCECIEIUIQIgQhCBGCECEIEYIQIQhBiBCECEGIEIQIQQhChCBECEKEIEQIQhAiBCFCECIEIUIQghAhCBGCECEIEYIQIUKEIEQIQoQg5LoBBaDPbQYiMoMAAAAASUVORK5CYII=";
#if defined(ESP32)
File file = SPIFFS.open("/green.png", FILE_WRITE);
#elif defined(ESP8266)
File file = SPIFFS.open("/green.png", "w");
#endif
file.print(greenImg);
file.close();
#if defined(ESP32)
file = SPIFFS.open("/bin2.dat", FILE_WRITE);
#elif defined(ESP8266)
file = SPIFFS.open("/bin2.dat", "w");
#endif
buf[0] = 'H';
buf[1] = 'E';
buf[2] = 'L';
buf[3] = 'L';
buf[4] = 'O';
file.write(buf, 5);
size_t i;
for (i = 0; i < 4; i++)
{
memset(buf, i + 1, 512);
file.write(buf, 512);
}
buf[0] = 'G';
buf[1] = 'O';
buf[2] = 'O';
buf[3] = 'D';
buf[4] = 'B';
buf[5] = 'Y';
buf[6] = 'E';
file.write(buf, 7);
file.close();
}
else
{
Serial.println("SPIFFS Monting Failed");
}
/** 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;
/** ########################################################
* Some properties of SMTPSession data and parameters pass to
* SMTP_Message class accept the pointer to constant char
* i.e. const char*.
*
* You may assign a string literal to that properties or function
* like below example.
*
* session.login.user_domain = "mydomain.net";
* session.login.user_domain = String("mydomain.net").c_str();
*
* or
*
* String doman = "mydomain.net";
* session.login.user_domain = domain.c_str();
*
* And
*
* String name = "Jack " + String("dawson");
* String email = "jack_dawson" + String(123) + "@mail.com";
*
* message.addRecipient(name.c_str(), email.c_str());
*
* message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str());
*
* or
*
* String header = "Message-ID: <abcde.fghij@gmail.com>";
* message.addHeader(header.c_str());
*
* ###########################################################
*/
/* 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("user1", "####@#####_dot_com");
/** Two alternative content versions are sending in this example e.g. plain text and html */
String htmlMsg = "<span style=\"color:#ff0000;\">This message contains 2 inline images and 2 attachment files.</span><br/><br/><img src=\"green.png\" width=\"100\" height=\"100\"> <img src=\"orange.png\" width=\"100\" height=\"100\">";
message.html.content = htmlMsg.c_str();
/** The HTML text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
message.text.content = "This message contains 2 inline images and 2 attachment files.\r\nThe inline images were not shown in the plain text message.";
message.text.charSet = "utf-8";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <user1@gmail.com>");
/* The attachment data item */
SMTP_Attachment att;
/** Set the inline image info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
att.descr.filename = "orange.png";
att.descr.mime = "image/png";
att.file.path = "/orange.png";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
att.file.storage_type = esp_mail_file_storage_type_sd;
/* Need to be base64 transfer encoding for inline image */
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The orange.png file is already base64 encoded file.
* Then set the content encoding to match the transfer encoding
* which no encoding was taken place prior to sending.
*/
att.descr.content_encoding = Content_Transfer_Encoding::enc_base64;
/* Add inline image to the message */
message.addInlineImage(att);
/** Set the attachment info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "bin1.dat";
att.descr.mime = "application/octet-stream"; //binary data
att.file.path = "/bin1.dat";
att.file.storage_type = esp_mail_file_storage_type_sd;
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add attachment to the message */
message.addAttachment(att);
/** Set the inline image info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "green.png";
att.descr.mime = "image/png";
att.file.path = "/green.png";
att.file.storage_type = esp_mail_file_storage_type_flash;
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
att.descr.content_encoding = Content_Transfer_Encoding::enc_base64;
message.addInlineImage(att);
/** Set the attachment info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "bin2.dat";
att.descr.mime = "application/octet-stream";
att.file.path = "/bin2.dat";
att.file.storage_type = esp_mail_file_storage_type_flash;
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,203 +1,203 @@
/**
* This example will send the Email which the
* message html and text body will be embedded as
* attachment or inline content.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending message as embedded files";
message.addRecipient("Admin", "####@#####_dot_com");
message.html.content = "<span style=\"color:#0055ff;\">This is html message</span>";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
/* Enable to send this message body as file */
message.html.embed.enable = true;
/* The name of embedded file */
message.html.embed.filename = "test.html";
/** The embedded type
* esp_mail_smtp_embed_message_type_attachment or 0
* esp_mail_smtp_embed_message_type_inline or 1
*/
message.html.embed.type = esp_mail_smtp_embed_message_type_attachment;
message.text.content = "This is simple plain text message";
message.text.charSet = "utf-8";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
message.text.embed.enable = true;
message.text.embed.filename = "test.txt";
message.text.embed.type = esp_mail_smtp_embed_message_type_inline;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/* Set the custom message header */
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email which the
* message html and text body will be embedded as
* attachment or inline content.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending message as embedded files";
message.addRecipient("Admin", "####@#####_dot_com");
message.html.content = "<span style=\"color:#0055ff;\">This is html message</span>";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
/* Enable to send this message body as file */
message.html.embed.enable = true;
/* The name of embedded file */
message.html.embed.filename = "test.html";
/** The embedded type
* esp_mail_smtp_embed_message_type_attachment or 0
* esp_mail_smtp_embed_message_type_inline or 1
*/
message.html.embed.type = esp_mail_smtp_embed_message_type_attachment;
message.text.content = "This is simple plain text message";
message.text.charSet = "utf-8";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
message.text.embed.enable = true;
message.text.embed.filename = "test.txt";
message.text.embed.type = esp_mail_smtp_embed_message_type_inline;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/* Set the custom message header */
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,187 +1,187 @@
/**
* This example will send the Email in enriched text version.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending enriched text Email";
message.addRecipient("Someone", "####@#####_dot_com");
message.text.content = "This is <bold><italic>enriched </italic></bold> <smaller>as defined in RFC 1896</smaller>\r\n\r\nIsn't it <bigger><bigger>cool?</bigger></bigger>";
message.text.content_type = "text/enriched";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email in enriched text version.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending enriched text Email";
message.addRecipient("Someone", "####@#####_dot_com");
message.text.content = "This is <bold><italic>enriched </italic></bold> <smaller>as defined in RFC 1896</smaller>\r\n\r\nIsn't it <bigger><bigger>cool?</bigger></bigger>";
message.text.content_type = "text/enriched";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,221 +1,221 @@
/**
* This example will send the Email in
* the html version.
*
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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;
/** ########################################################
* Some properties of SMTPSession data and parameters pass to
* SMTP_Message class accept the pointer to constant char
* i.e. const char*.
*
* You may assign a string literal to that properties or function
* like below example.
*
* session.login.user_domain = "mydomain.net";
* session.login.user_domain = String("mydomain.net").c_str();
*
* or
*
* String doman = "mydomain.net";
* session.login.user_domain = domain.c_str();
*
* And
*
* String name = "Jack " + String("dawson");
* String email = "jack_dawson" + String(123) + "@mail.com";
*
* message.addRecipient(name.c_str(), email.c_str());
*
* message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str());
*
* or
*
* String header = "Message-ID: <abcde.fghij@gmail.com>";
* message.addHeader(header.c_str());
*
* ###########################################################
*/
/* 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;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending html Email";
message.addRecipient("Admin", "####@#####_dot_com");
String htmlMsg = "<p>This is the <span style=\"color:#ff0000;\">html text</span> message.</p><p>The message was sent via ESP device.</p>";
message.html.content = htmlMsg.c_str();
/** The html text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email in
* the html version.
*
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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;
/** ########################################################
* Some properties of SMTPSession data and parameters pass to
* SMTP_Message class accept the pointer to constant char
* i.e. const char*.
*
* You may assign a string literal to that properties or function
* like below example.
*
* session.login.user_domain = "mydomain.net";
* session.login.user_domain = String("mydomain.net").c_str();
*
* or
*
* String doman = "mydomain.net";
* session.login.user_domain = domain.c_str();
*
* And
*
* String name = "Jack " + String("dawson");
* String email = "jack_dawson" + String(123) + "@mail.com";
*
* message.addRecipient(name.c_str(), email.c_str());
*
* message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str());
*
* or
*
* String header = "Message-ID: <abcde.fghij@gmail.com>";
* message.addHeader(header.c_str());
*
* ###########################################################
*/
/* 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;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending html Email";
message.addRecipient("Admin", "####@#####_dot_com");
String htmlMsg = "<p>This is the <span style=\"color:#ff0000;\">html text</span> message.</p><p>The message was sent via ESP device.</p>";
message.html.content = htmlMsg.c_str();
/** The html text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,229 +1,229 @@
/**
* This example will send the Email with media as parallen attachments
* e.g. audio and images and play or display them simultaneously on the Email client.
*
* This depends on the Mail client supports.
*
* The html and text version messages will be sent.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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>
/* This is for attachment data */
#include "data.h"
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login
*/
#define SMTP_HOST "################"
/** 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 esp_mail_smtp_port_587
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "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 parallel attachments";
message.addRecipient("user1", "####@#####_dot_com");
message.html.content = "<span style=\"color:#ff0000;\">This message contains image and audio file which will play on the Mail client in parallel or simultaneously (depends on the client supports).";
/** The HTML text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
message.text.content = "This message contains image and audio file which will play on the Mail client in parallel or simultaneously (depends on the client supports).";
message.text.charSet = "us-ascii";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <user1@gmail.com>");
/* 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 = "haun.png";
att.descr.mime = "image/png";
att.blob.data = shaun_png;
att.blob.size = sizeof(shaun_png);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
message.addParallelAttachment(att);
/** Set the attachment info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "mu_law.wav";
att.descr.mime = "audio/basic";
att.blob.data = mu_law_wave;
att.blob.size = sizeof(mu_law_wave);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
message.addParallelAttachment(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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email with media as parallen attachments
* e.g. audio and images and play or display them simultaneously on the Email client.
*
* This depends on the Mail client supports.
*
* The html and text version messages will be sent.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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>
/* This is for attachment data */
#include "data.h"
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login
*/
#define SMTP_HOST "################"
/** 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 esp_mail_smtp_port_587
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "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 parallel attachments";
message.addRecipient("user1", "####@#####_dot_com");
message.html.content = "<span style=\"color:#ff0000;\">This message contains image and audio file which will play on the Mail client in parallel or simultaneously (depends on the client supports).";
/** The HTML text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
message.text.content = "This message contains image and audio file which will play on the Mail client in parallel or simultaneously (depends on the client supports).";
message.text.charSet = "us-ascii";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <user1@gmail.com>");
/* 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 = "haun.png";
att.descr.mime = "image/png";
att.blob.data = shaun_png;
att.blob.size = sizeof(shaun_png);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
message.addParallelAttachment(att);
/** Set the attachment info e.g.
* file name, MIME type, file path, file storage type,
* transfer encoding and content encoding
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "mu_law.wav";
att.descr.mime = "audio/basic";
att.blob.data = mu_law_wave;
att.blob.size = sizeof(mu_law_wave);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
message.addParallelAttachment(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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,252 +1,252 @@
/**
* This example will send the Email in plain text version
* with rfc822 message attachment which the rfc822 message
* also contains its attachement.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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>
/* This is for attachment data */
#include "image.h"
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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();
Serial.println("Connect to NTP server and set the device time\r\nPlease wait...\r\n");
float timeZone = 3;//GMT+3
float daylightOffset = 0;
/* Set the device time */
MailClient.Time.setClock(timeZone, daylightOffset);
/** 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;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending Email with rfc822 attachment";
message.addRecipient("Someone", "####@#####_dot_com");
message.text.content = "This is simple plain text message with rfc822 attachment";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/* Set the custom message header */
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
SMTP_Message rfc822;
rfc822.messageID = "1234@local.machine.example";
rfc822.from.name = "rob";
rfc822.from.email = "rob@example.com";
rfc822.sender.name = "steve";
rfc822.sender.email = "steve@example.com";
String dt = MailClient.Time.getDateTimeString();
rfc822.date = dt.c_str();
rfc822.subject = "Test rfc822 message";
rfc822.comment = "This is comment";
rfc822.addRecipient("joe", "joe@example.com");
rfc822.response.reply_to = "rob@example.com";
rfc822.text.charSet = "utf-8";
rfc822.text.content = "This is rfc822 text message";
rfc822.text.transfer_encoding = Content_Transfer_Encoding::enc_qp;
rfc822.html.charSet = "utf-8";
rfc822.html.content = "This is rfc822 html message";
rfc822.html.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* The attachment data item */
SMTP_Attachment att;
/** Set the attachment info e.g.
* file name, MIME type, BLOB data, BLOB data size,
* and transfer encoding
*/
att.descr.filename = "firebase_logo.png";
att.descr.mime = "image/png";
att.blob.data = firebase_png;
att.blob.size = sizeof(firebase_png);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add the attachment to the rfc822 message */
rfc822.addAttachment(att);
/* Prepare other attachment data */
uint8_t *a = new uint8_t[512];
int j = 0;
for (int i = 0; i < 512; i++)
{
a[i] = j;
j++;
if (j > 255)
j = 0;
}
/** Set the attachment info e.g.
* file name, MIME type, BLOB data, BLOB data size.
* The default transfer encoding is base64.
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "test.dat";
att.descr.mime = "application/octet-stream";
att.blob.data = a;
att.blob.size = 512;
/* Add this attachment to the message */
message.addAttachment(att);
/* Add rfc822 message in the message */
message.addMessage(rfc822);
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email in plain text version
* with rfc822 message attachment which the rfc822 message
* also contains its attachement.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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>
/* This is for attachment data */
#include "image.h"
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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();
Serial.println("Connect to NTP server and set the device time\r\nPlease wait...\r\n");
float timeZone = 3;//GMT+3
float daylightOffset = 0;
/* Set the device time */
MailClient.Time.setClock(timeZone, daylightOffset);
/** 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;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending Email with rfc822 attachment";
message.addRecipient("Someone", "####@#####_dot_com");
message.text.content = "This is simple plain text message with rfc822 attachment";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/* Set the custom message header */
message.addHeader("Message-ID: <abcde.fghij@gmail.com>");
SMTP_Message rfc822;
rfc822.messageID = "1234@local.machine.example";
rfc822.from.name = "rob";
rfc822.from.email = "rob@example.com";
rfc822.sender.name = "steve";
rfc822.sender.email = "steve@example.com";
String dt = MailClient.Time.getDateTimeString();
rfc822.date = dt.c_str();
rfc822.subject = "Test rfc822 message";
rfc822.comment = "This is comment";
rfc822.addRecipient("joe", "joe@example.com");
rfc822.response.reply_to = "rob@example.com";
rfc822.text.charSet = "utf-8";
rfc822.text.content = "This is rfc822 text message";
rfc822.text.transfer_encoding = Content_Transfer_Encoding::enc_qp;
rfc822.html.charSet = "utf-8";
rfc822.html.content = "This is rfc822 html message";
rfc822.html.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* The attachment data item */
SMTP_Attachment att;
/** Set the attachment info e.g.
* file name, MIME type, BLOB data, BLOB data size,
* and transfer encoding
*/
att.descr.filename = "firebase_logo.png";
att.descr.mime = "image/png";
att.blob.data = firebase_png;
att.blob.size = sizeof(firebase_png);
att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/* Add the attachment to the rfc822 message */
rfc822.addAttachment(att);
/* Prepare other attachment data */
uint8_t *a = new uint8_t[512];
int j = 0;
for (int i = 0; i < 512; i++)
{
a[i] = j;
j++;
if (j > 255)
j = 0;
}
/** Set the attachment info e.g.
* file name, MIME type, BLOB data, BLOB data size.
* The default transfer encoding is base64.
*/
message.resetAttachItem(att); //Clear the attach item data to reuse
att.descr.filename = "test.dat";
att.descr.mime = "application/octet-stream";
att.blob.data = a;
att.blob.size = 512;
/* Add this attachment to the message */
message.addAttachment(att);
/* Add rfc822 message in the message */
message.addMessage(rfc822);
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,245 +1,245 @@
/**
* This example will send multiple messages which
* the session was keep open during sending.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 esp_mail_smtp_port_587
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "First Email with session reusage";
message.addRecipient("Admin1", "####@#####_dot_com");
message.addRecipient("Admin2", "####@#####_dot_com");
message.addCc("####@#####_dot_com");
message.addBcc("####@#####_dot_com");
message.html.content = "<p>This is the <span style=\"color:#ff0000;\">first message</span>.</p>";
/** The HTML text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
/** The option to add soft line break to to the message for
* the long text message > 78 characters (rfc 3676)
* Some Servers may not compliant with the standard.
*/
message.text.flowed = true;
message.text.content = "This is the first message";
message.text.charSet = "us-ascii";
message.html.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <Admin1@gmail.com>");
Serial.println();
Serial.println("Sending first Email...");
/* Connect to server with the session config */
if (!smtp.connect(&session))
return;
/** Start sending the first Email and keep open the session
* The third parameter is for close the session.
*/
if (!MailClient.sendMail(&smtp, &message, false))
Serial.println("Error sending Email, " + smtp.errorReason());
/* To clear all message data */
//message.clear();
/** Clear primary recipients, Cc recipients, Bcc recipients, custom headers
* attachments and inline images
*/
message.clearRecipients();
message.clearCc();
message.clearBcc();
//message.clearAttachments();
//message.clearInlineimages();
message.subject = "Second Email with session reusage";
message.addRecipient("Admin3", "####@#####_dot_com");
message.addRecipient("Admin4", "####@#####_dot_com");
message.addCc("####@#####_dot_com");
message.addBcc("####@#####_dot_com");
message.html.content = "<p>This is the <span style=\"color:#ff0000;\">second message</span>.</p>";
message.html.charSet = "us-ascii";
message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
message.text.content = "This is the second message";
message.text.charSet = "UTF-8";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_qp;
/* Set the custom message header */
message.addHeader("Message-ID: <Admin3@gmail.com>");
Serial.println();
Serial.println("Sending second Email...");
/* Start sending the second mail 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send multiple messages which
* the session was keep open during sending.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 esp_mail_smtp_port_587
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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 = "mydomain.net";
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "First Email with session reusage";
message.addRecipient("Admin1", "####@#####_dot_com");
message.addRecipient("Admin2", "####@#####_dot_com");
message.addCc("####@#####_dot_com");
message.addBcc("####@#####_dot_com");
message.html.content = "<p>This is the <span style=\"color:#ff0000;\">first message</span>.</p>";
/** The HTML text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.html.charSet = "utf-8";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.html.transfer_encoding = Content_Transfer_Encoding::enc_qp;
/** The option to add soft line break to to the message for
* the long text message > 78 characters (rfc 3676)
* Some Servers may not compliant with the standard.
*/
message.text.flowed = true;
message.text.content = "This is the first message";
message.text.charSet = "us-ascii";
message.html.transfer_encoding = Content_Transfer_Encoding::enc_base64;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_normal;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <Admin1@gmail.com>");
Serial.println();
Serial.println("Sending first Email...");
/* Connect to server with the session config */
if (!smtp.connect(&session))
return;
/** Start sending the first Email and keep open the session
* The third parameter is for close the session.
*/
if (!MailClient.sendMail(&smtp, &message, false))
Serial.println("Error sending Email, " + smtp.errorReason());
/* To clear all message data */
//message.clear();
/** Clear primary recipients, Cc recipients, Bcc recipients, custom headers
* attachments and inline images
*/
message.clearRecipients();
message.clearCc();
message.clearBcc();
//message.clearAttachments();
//message.clearInlineimages();
message.subject = "Second Email with session reusage";
message.addRecipient("Admin3", "####@#####_dot_com");
message.addRecipient("Admin4", "####@#####_dot_com");
message.addCc("####@#####_dot_com");
message.addBcc("####@#####_dot_com");
message.html.content = "<p>This is the <span style=\"color:#ff0000;\">second message</span>.</p>";
message.html.charSet = "us-ascii";
message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
message.text.content = "This is the second message";
message.text.charSet = "UTF-8";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_qp;
/* Set the custom message header */
message.addHeader("Message-ID: <Admin3@gmail.com>");
Serial.println();
Serial.println("Sending second Email...");
/* Start sending the second mail 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,219 +1,219 @@
/**
* This example will send the Email in plain text version.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The sign in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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;
/** ########################################################
* Some properties of SMTPSession data and parameters pass to
* SMTP_Message class accept the pointer to constant char
* i.e. const char*.
*
* You may assign a string literal to that properties or function
* like below example.
*
* session.login.user_domain = "mydomain.net";
* session.login.user_domain = String("mydomain.net").c_str();
*
* or
*
* String doman = "mydomain.net";
* session.login.user_domain = domain.c_str();
*
* And
*
* String name = "Jack " + String("dawson");
* String email = "jack_dawson" + String(123) + "@mail.com";
*
* message.addRecipient(name.c_str(), email.c_str());
*
* message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str());
*
* or
*
* String header = "Message-ID: <abcde.fghij@gmail.com>";
* message.addHeader(header.c_str());
*
* ###########################################################
*/
/* 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;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending plain text Email";
message.addRecipient("Someone", "####@#####_dot_com");
String textMsg = "This is simple plain text message";
message.text.content = textMsg.c_str();
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email in plain text version.
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The sign in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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;
/** ########################################################
* Some properties of SMTPSession data and parameters pass to
* SMTP_Message class accept the pointer to constant char
* i.e. const char*.
*
* You may assign a string literal to that properties or function
* like below example.
*
* session.login.user_domain = "mydomain.net";
* session.login.user_domain = String("mydomain.net").c_str();
*
* or
*
* String doman = "mydomain.net";
* session.login.user_domain = domain.c_str();
*
* And
*
* String name = "Jack " + String("dawson");
* String email = "jack_dawson" + String(123) + "@mail.com";
*
* message.addRecipient(name.c_str(), email.c_str());
*
* message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str());
*
* or
*
* String header = "Message-ID: <abcde.fghij@gmail.com>";
* message.addHeader(header.c_str());
*
* ###########################################################
*/
/* 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;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending plain text Email";
message.addRecipient("Someone", "####@#####_dot_com");
String textMsg = "This is simple plain text message";
message.text.content = textMsg.c_str();
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,229 +1,229 @@
/**
* This example will send the Email in plain text version
* with the quoted text and long line text.
*
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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;
/** ########################################################
* Some properties of SMTPSession data and parameters pass to
* SMTP_Message class accept the pointer to constant char
* i.e. const char*.
*
* You may assign a string literal to that properties or function
* like below example.
*
* session.login.user_domain = "mydomain.net";
* session.login.user_domain = String("mydomain.net").c_str();
*
* or
*
* String doman = "mydomain.net";
* session.login.user_domain = domain.c_str();
*
* And
*
* String name = "Jack " + String("dawson");
* String email = "jack_dawson" + String(123) + "@mail.com";
*
* message.addRecipient(name.c_str(), email.c_str());
*
* message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str());
*
* or
*
* String header = "Message-ID: <abcde.fghij@gmail.com>";
* message.addHeader(header.c_str());
*
* ###########################################################
*/
/* 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;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending flowed plain text Email";
message.addRecipient("Someone", "####@#####_dot_com");
/** The option to add soft line break to to the message for
* the long text message > 78 characters (rfc 3676)
* Some Servers may not compliant with the standard.
*/
message.text.flowed = true;
/** if the option message.text.flowed is true,
* the following plain text message will be wrapped.
*/
message.text.content = "The text below is the long quoted text which breaks into several lines.\r\n\r\n>> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\r\n\r\nThis is the normal short text.\r\n\r\nAnother long text, abcdefg hijklmnop qrstuv wxyz abcdefg hijklmnop qrstuv wxyz abcdefg hijklmnop qrstuv wxyz.";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}
/**
* This example will send the Email in plain text version
* with the quoted text and long line text.
*
*
* Created by K. Suwatchai (Mobizt)
*
* Email: suwatchai@outlook.com
*
* Github: 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 "################"
#define WIFI_PASSWORD "################"
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com
* For yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
* and use the app password as password with your yahoo mail account to login.
* The google app password signin is also available https://support.google.com/mail/answer/185833?hl=en
*/
#define SMTP_HOST "################"
/** 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 25
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* 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;
/** ########################################################
* Some properties of SMTPSession data and parameters pass to
* SMTP_Message class accept the pointer to constant char
* i.e. const char*.
*
* You may assign a string literal to that properties or function
* like below example.
*
* session.login.user_domain = "mydomain.net";
* session.login.user_domain = String("mydomain.net").c_str();
*
* or
*
* String doman = "mydomain.net";
* session.login.user_domain = domain.c_str();
*
* And
*
* String name = "Jack " + String("dawson");
* String email = "jack_dawson" + String(123) + "@mail.com";
*
* message.addRecipient(name.c_str(), email.c_str());
*
* message.addHeader(String("Message-ID: <abcde.fghij@gmail.com>").c_str());
*
* or
*
* String header = "Message-ID: <abcde.fghij@gmail.com>";
* message.addHeader(header.c_str());
*
* ###########################################################
*/
/* 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;
/* Set the message headers */
message.sender.name = "ESP Mail";
message.sender.email = AUTHOR_EMAIL;
message.subject = "Test sending flowed plain text Email";
message.addRecipient("Someone", "####@#####_dot_com");
/** The option to add soft line break to to the message for
* the long text message > 78 characters (rfc 3676)
* Some Servers may not compliant with the standard.
*/
message.text.flowed = true;
/** if the option message.text.flowed is true,
* the following plain text message will be wrapped.
*/
message.text.content = "The text below is the long quoted text which breaks into several lines.\r\n\r\n>> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\r\n\r\nThis is the normal short text.\r\n\r\nAnother long text, abcdefg hijklmnop qrstuv wxyz abcdefg hijklmnop qrstuv wxyz abcdefg hijklmnop qrstuv wxyz.";
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = "us-ascii";
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
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: <abcde.fghij@gmail.com>");
/* 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("----------------");
Serial.printf("Message sent success: %d\n", status.completedCount());
Serial.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);
localtime_r(&result.timesstamp, &dt);
Serial.printf("Message No: %d\n", i + 1);
Serial.printf("Status: %s\n", result.completed ? "success" : "failed");
Serial.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);
Serial.printf("Recipient: %s\n", result.recipients);
Serial.printf("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

View File

@ -1,363 +1,363 @@
/**
* This example will set the argument to the flags and read the message.
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Message UID to fetch or read e.g. 100 */
config.fetch.uid = "100";
/* Set seen flag */
//config.fetch.set_seen = true;
/* Search criteria */
config.search.criteria = "";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = true;
config.download.text = true;
config.download.html = true;
config.download.attachment = true;
config.download.inlineImg = true;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
/** Set \Seen and \Answered to flags for message with UID 100
* The seesion will keep open.
*/
if (MailClient.setFlag(&imap, 100, "\\Seen \\Answered", false))
Serial.println("Setting FLAG success");
else
Serial.println("Error, setting FLAG");
/* Add \Seen and \Answered to flags for message with UID 100 */
//MailClient.addFlag(imap, 100, "\\Seen \\Answered", false);
/* Remove \Seen and \Answered from flags for message with UID 100 */
//MailClient.removeFlag(imap, 100, "\\Seen \\Answered", false);
/* Read or search the Email and close the session */
MailClient.readMail(&imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
void loop()
{
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
Serial.printf("Free Heap: %d", ESP.getFreeHeap());
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}
/**
* This example will set the argument to the flags and read the message.
*
* Email: suwatchai@outlook.com
*
* Github: https://github.com/mobizt/ESP-Mail-Client
*
* Copyright (c) 2021 mobizt
*
*/
/** To receive Email using Gmail, IMAP option should be enabled. https://support.google.com/mail/answer/7126229?hl=en
* and also https://accounts.google.com/b/0/DisplayUnlockCaptcha
*
*/
/** For ESP8266, with BearSSL WiFi Client
* The memory reserved for completed valid SSL response from IMAP is 16 kbytes which
* may cause your device out of memory reset in case the memory
* allocation error.
*/
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <ESP_Mail_Client.h>
#define WIFI_SSID "################"
#define WIFI_PASSWORD "################"
/* The imap host name e.g. imap.gmail.com for GMail or outlook.office365.com for Outlook */
#define IMAP_HOST "################"
/** The imap port e.g.
* 143 or esp_mail_imap_port_143
* 993 or esp_mail_imap_port_993
*/
#define IMAP_PORT 993
/* The log in credentials */
#define AUTHOR_EMAIL "################"
#define AUTHOR_PASSWORD "################"
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status);
/* Print the list of mailbox folders */
void printAllMailboxesInfo(IMAPSession &imap);
/* Print the selected folder info */
void printSelectedMailboxInfo(IMAPSession &imap);
/* Print all messages from the message list */
void printMessages(IMAPSession &imap);
/* Print all rfc822 messages included in the message */
void printRFC822Messages(IMAP_MSG_Item &msg);
/* Print all attachments info from the message */
void printAttacements(IMAP_MSG_Item &msg);
/* The IMAP Session object used for Email reading */
IMAPSession imap;
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
*/
imap.debug(1);
/* Set the callback function to get the reading results */
imap.callback(imapCallback);
/** In case the SD card/adapter was used for the file storagge, the SPI pins can be configure from
* MailClient.sdBegin function which may be different for ESP32 and ESP8266
* For ESP32, assign all of SPI pins
* MailClient.sdBegin(14,2,15,13)
* Which SCK = 14, MISO = 2, MOSI = 15 and SS = 13
* And for ESP8266, assign the CS pins of SPI port
* MailClient.sdBegin(15)
* Which pin 15 is the CS pin of SD card adapter
*/
/* Declare the session config data */
ESP_Mail_Session session;
/* Set the session config */
session.server.host_name = IMAP_HOST;
session.server.port = IMAP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
/* Setup the configuration for searching or fetching operation and its result */
IMAP_Config config;
/* Message UID to fetch or read e.g. 100 */
config.fetch.uid = "100";
/* Set seen flag */
//config.fetch.set_seen = true;
/* Search criteria */
config.search.criteria = "";
/* Also search the unseen message */
config.search.unseen_msg = true;
/* Set the storage to save the downloaded files and attachments */
config.storage.saved_path = "/email_data";
/** The file storage type e.g.
* esp_mail_file_storage_type_none,
* esp_mail_file_storage_type_flash, and
* esp_mail_file_storage_type_sd
*/
config.storage.type = esp_mail_file_storage_type_flash;
/** Set to download heades, text and html messaeges,
* attachments and inline images respectively.
*/
config.download.header = true;
config.download.text = true;
config.download.html = true;
config.download.attachment = true;
config.download.inlineImg = true;
/** Set to enable the results i.e. html and text messaeges
* which the content stored in the IMAPSession object is limited
* by the option config.limit.msg_size.
* The whole message can be download through config.download.text
* or config.download.html which not depends on these enable options.
*/
config.enable.html = true;
config.enable.text = true;
/* Set to enable the sort the result by message UID in the ascending order */
config.enable.recent_sort = true;
/* Set to report the download progress via the default serial port */
config.enable.download_status = true;
/* Set the limit of number of messages in the search results */
config.limit.search = 5;
/** Set the maximum size of message stored in
* IMAPSession object in byte
*/
config.limit.msg_size = 512;
/** Set the maximum attachments and inline images files size
* that can be downloaded in byte.
* The file which its size is largger than this limit may be saved
* as truncated file.
*/
config.limit.attachment_size = 1024 * 1024 * 5;
/* Connect to server with the session and config */
if (!imap.connect(&session, &config))
return;
/* {Optional] */
printAllMailboxesInfo(imap);
/* Open or select the mailbox folder to read or search the message */
if (!imap.selectFolder("INBOX"))
return;
/* {Optional] */
printSelectedMailboxInfo(imap);
/** Set \Seen and \Answered to flags for message with UID 100
* The seesion will keep open.
*/
if (MailClient.setFlag(&imap, 100, "\\Seen \\Answered", false))
Serial.println("Setting FLAG success");
else
Serial.println("Error, setting FLAG");
/* Add \Seen and \Answered to flags for message with UID 100 */
//MailClient.addFlag(imap, 100, "\\Seen \\Answered", false);
/* Remove \Seen and \Answered from flags for message with UID 100 */
//MailClient.removeFlag(imap, 100, "\\Seen \\Answered", false);
/* Read or search the Email and close the session */
MailClient.readMail(&imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
}
void loop()
{
}
/* Callback function to get the Email reading status */
void imapCallback(IMAP_Status status)
{
/* Print the current status */
Serial.println(status.info());
/* Show the result when reading finished */
if (status.success())
{
/* Print the result */
printMessages(imap);
/* Clear all stored data in IMAPSession object */
imap.empty();
Serial.printf("Free Heap: %d", ESP.getFreeHeap());
}
}
void printAllMailboxesInfo(IMAPSession &imap)
{
/* Declare the folder collection class to get the list of mailbox folders */
FoldersCollection folders;
/* Get the mailbox folders */
if (imap.getFolders(folders))
{
for (size_t i = 0; i < folders.size(); i++)
{
/* Iterate each folder info using the folder info item data */
FolderInfo folderInfo = folders.info(i);
Serial.printf("%s%s%s", i == 0 ? "\nAvailable folders: " : ", ", folderInfo.name, i == folders.size() - 1 ? "\n" : "");
}
}
}
void printSelectedMailboxInfo(IMAPSession &imap)
{
/* Declare the selected folder info class to get the info of selected mailbox folder */
SelectedFolderInfo sFolder = imap.selectedFolder();
/* Show the mailbox info */
Serial.printf("\nInfo of the selected folder\nTotal Messages: %d\n", sFolder.msgCount());
Serial.printf("Predicted next UID: %d\n", sFolder.nextUID());
for (size_t i = 0; i < sFolder.flagCount(); i++)
Serial.printf("%s%s%s", i == 0 ? "Flags: " : ", ", sFolder.flag(i).c_str(), i == sFolder.flagCount() - 1 ? "\n" : "");
}
void printRFC822Messages(IMAP_MSG_Item &msg)
{
Serial.printf("RFC822 Messages: %d message(s)\n****************************\n", msg.rfc822.size());
for (size_t j = 0; j < msg.rfc822.size(); j++)
{
IMAP_MSG_Item rfc822 = msg.rfc822[j];
Serial.printf("%d. \n", j + 1);
Serial.printf("Messsage ID: %s\n", rfc822.messageID);
Serial.printf("From: %s\n", rfc822.from);
Serial.printf("Sender: %s\n", rfc822.sender);
Serial.printf("To: %s\n", rfc822.to);
Serial.printf("CC: %s\n", rfc822.cc);
Serial.printf("Subject: %s\n", rfc822.subject);
Serial.printf("Date: %s\n", rfc822.date);
Serial.printf("Reply-To: %s\n", rfc822.reply_to);
Serial.printf("Return-Path: %s\n", rfc822.return_path);
Serial.printf("Comment: %s\n", rfc822.comment);
Serial.printf("Keyword: %s\n", rfc822.keyword);
Serial.printf("Text Message: %s\n", rfc822.text.content);
Serial.printf("Text Message Charset: %s\n", rfc822.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", rfc822.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", rfc822.html.content);
Serial.printf("HTML Message Charset: %s\n", rfc822.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", rfc822.html.transfer_encoding);
if (rfc822.attachments.size() > 0)
printAttacements(rfc822);
}
}
void printAttacements(IMAP_MSG_Item &msg)
{
Serial.printf("Attachment: %d file(s)\n****************************\n", msg.attachments.size());
for (size_t j = 0; j < msg.attachments.size(); j++)
{
IMAP_Attach_Item att = msg.attachments[j];
/** att.type can be
* esp_mail_att_type_none or 0
* esp_mail_att_type_attachment or 1
* esp_mail_att_type_inline or 2
*/
Serial.printf("%d. Filename: %s, Name: %s, Size: %d, MIME: %s, Type: %s, Creation Date: %s\n", j + 1, att.filename, att.name, att.size, att.mime, att.type == esp_mail_att_type_attachment ? "attachment" : "inline", att.creationDate);
}
Serial.println();
}
void printMessages(IMAPSession &imap)
{
/* Get the message list from the message list data */
IMAP_MSG_List msgList = imap.data();
for (size_t i = 0; i < msgList.msgItems.size(); i++)
{
/* Iterate to get each message data through the message item data */
IMAP_MSG_Item msg = msgList.msgItems[i];
Serial.println("################################");
Serial.printf("Messsage Number: %s\n", msg.msgNo);
Serial.printf("Messsage UID: %s\n", msg.UID);
Serial.printf("Messsage ID: %s\n", msg.ID);
Serial.printf("Accept Language: %s\n", msg.acceptLang);
Serial.printf("Content Language: %s\n", msg.contentLang);
Serial.printf("From: %s\n", msg.from);
Serial.printf("From Charset: %s\n", msg.fromCharset);
Serial.printf("To: %s\n", msg.to);
Serial.printf("To Charset: %s\n", msg.toCharset);
Serial.printf("CC: %s\n", msg.cc);
Serial.printf("CC Charset: %s\n", msg.ccCharset);
Serial.printf("Date: %s\n", msg.date);
Serial.printf("Subject: %s\n", msg.subject);
Serial.printf("Subject Charset: %s\n", msg.subjectCharset);
/* If the result contains the message info (Fetch mode) */
if (!imap.headerOnly())
{
Serial.printf("Text Message: %s\n", msg.text.content);
Serial.printf("Text Message Charset: %s\n", msg.text.charSet);
Serial.printf("Text Message Transfer Encoding: %s\n", msg.text.transfer_encoding);
Serial.printf("HTML Message: %s\n", msg.html.content);
Serial.printf("HTML Message Charset: %s\n", msg.html.charSet);
Serial.printf("HTML Message Transfer Encoding: %s\n\n", msg.html.transfer_encoding);
if (msg.attachments.size() > 0)
printAttacements(msg);
if (msg.rfc822.size() > 0)
printRFC822Messages(msg);
}
Serial.println();
}
}

View File

@ -1,127 +1,127 @@
######################################
# Syntax Coloring Map ESP Mail Client
######################################
#######################################
# Classes and Structured Type (KEYWORD1)
#######################################
MailClient KEYWORD1
IMAPSession KEYWORD1
SMTPSession KEYWORD1
SMTP_Message KEYWORD1
IMAP_Config KEYWORD1
FoldersCollection KEYWORD1
imapStatusCallback KEYWORD1
IMAP_MSG_List KEYWORD1
SelectedFolderInfo KEYWORD1
ESP_Mail_Session KEYWORD1
smtpStatusCallback KEYWORD1
SMTP_Attachment KEYWORD1
SMTP_Result KEYWORD1
IMAP_MSG_Item KEYWORD1
Content_Transfer_Encoding KEYWORD1
MessageList KEYWORD1
###############################################
# Methods and Functions (KEYWORD2)
###############################################
sendMail KEYWORD2
readMail KEYWORD2
setFlag KEYWORD2
addFlag KEYWORD2
removeFlag KEYWORD2
sdBegin KEYWORD2
sdMMCBegin KEYWORD2
connect KEYWORD2
closeSession KEYWORD2
debug KEYWORD2
getFolders KEYWORD2
selectFolder KEYWORD2
openFolder KEYWORD2
closeFolder KEYWORD2
callback KEYWORD2
headerOnly KEYWORD2
data KEYWORD2
selectedFolder KEYWORD2
errorReason KEYWORD2
empty KEYWORD2
resetAttachItem KEYWORD2
clear KEYWORD2
clearInlineimages KEYWORD2
clearAttachments KEYWORD2
clearRFC822Messages KEYWORD2
clearRecipients KEYWORD2
clearCc KEYWORD2
clearBcc KEYWORD2
clearHeader KEYWORD2
addAttachment KEYWORD2
addParallelAttachment KEYWORD2
addInlineImage KEYWORD2
addMessage KEYWORD2
addRecipient KEYWORD2
addCc KEYWORD2
addBcc KEYWORD2
addHeader KEYWORD2
info KEYWORD2
successs KEYWORD2
completedCount KEYWORD2
failedCount KEYWORD2
getItem KEYWORD2
size KEYWORD2
flagCount KEYWORD2
msgCount KEYWORD2
nextUID KEYWORD2
searchCount KEYWORD2
availableMessages KEYWORD2
flag KEYWORD2
setClock KEYWORD2
getUnixTime KEYWORD2
getTimestamp KEYWORD2
getYear KEYWORD2
getMonth KEYWORD2
getDay KEYWORD2
getDayOfWeek KEYWORD2
getDayOfWeekString KEYWORD2
getHour KEYWORD2
getMin KEYWORD2
getSecond KEYWORD2
getNumberOfDayThisYear KEYWORD2
getTotalDays KEYWORD2
dayofWeek KEYWORD2
getCurrentSecond KEYWORD2
getCurrentTimestamp KEYWORD2
getTimeFromSec KEYWORD2
getDateTimeString KEYWORD2
copyMessages KEYWORD2
deleteMessages KEYWORD2
createFolder KEYWORD2
deleteFolder KEYWORD2
#######################################
# Struct (KEYWORD3)
#######################################
esp_mail_email_info_t KEYWORD3
esp_mail_plain_body_t KEYWORD3
esp_mail_html_body_t KEYWORD3
esp_mail_smtp_msg_response_t KEYWORD3
esp_mail_smtp_enable_option_t KEYWORD3
esp_mail_email_info_t KEYWORD3
esp_mail_folder_info_item_t KEYWORD3
esp_mail_sesson_sever_config_t KEYWORD3
esp_mail_sesson_login_config_t KEYWORD3
esp_mail_sesson_secure_config_t KEYWORD3
esp_mail_sesson_cert_config_t KEYWORD3
esp_mail_imap_fetch_config_t KEYWORD3
esp_mail_imap_search_config_t KEYWORD3
esp_mail_imap_limit_config_t KEYWORD3
esp_mail_imap_enable_config_t KEYWORD3
esp_mail_imap_download_config_t KEYWORD3
esp_mail_imap_storage_config_t KEYWORD3
esp_mail_file_storage_type_none KEYWORD3
esp_mail_file_storage_type_flash KEYWORD3
######################################
# Syntax Coloring Map ESP Mail Client
######################################
#######################################
# Classes and Structured Type (KEYWORD1)
#######################################
MailClient KEYWORD1
IMAPSession KEYWORD1
SMTPSession KEYWORD1
SMTP_Message KEYWORD1
IMAP_Config KEYWORD1
FoldersCollection KEYWORD1
imapStatusCallback KEYWORD1
IMAP_MSG_List KEYWORD1
SelectedFolderInfo KEYWORD1
ESP_Mail_Session KEYWORD1
smtpStatusCallback KEYWORD1
SMTP_Attachment KEYWORD1
SMTP_Result KEYWORD1
IMAP_MSG_Item KEYWORD1
Content_Transfer_Encoding KEYWORD1
MessageList KEYWORD1
###############################################
# Methods and Functions (KEYWORD2)
###############################################
sendMail KEYWORD2
readMail KEYWORD2
setFlag KEYWORD2
addFlag KEYWORD2
removeFlag KEYWORD2
sdBegin KEYWORD2
sdMMCBegin KEYWORD2
connect KEYWORD2
closeSession KEYWORD2
debug KEYWORD2
getFolders KEYWORD2
selectFolder KEYWORD2
openFolder KEYWORD2
closeFolder KEYWORD2
callback KEYWORD2
headerOnly KEYWORD2
data KEYWORD2
selectedFolder KEYWORD2
errorReason KEYWORD2
empty KEYWORD2
resetAttachItem KEYWORD2
clear KEYWORD2
clearInlineimages KEYWORD2
clearAttachments KEYWORD2
clearRFC822Messages KEYWORD2
clearRecipients KEYWORD2
clearCc KEYWORD2
clearBcc KEYWORD2
clearHeader KEYWORD2
addAttachment KEYWORD2
addParallelAttachment KEYWORD2
addInlineImage KEYWORD2
addMessage KEYWORD2
addRecipient KEYWORD2
addCc KEYWORD2
addBcc KEYWORD2
addHeader KEYWORD2
info KEYWORD2
successs KEYWORD2
completedCount KEYWORD2
failedCount KEYWORD2
getItem KEYWORD2
size KEYWORD2
flagCount KEYWORD2
msgCount KEYWORD2
nextUID KEYWORD2
searchCount KEYWORD2
availableMessages KEYWORD2
flag KEYWORD2
setClock KEYWORD2
getUnixTime KEYWORD2
getTimestamp KEYWORD2
getYear KEYWORD2
getMonth KEYWORD2
getDay KEYWORD2
getDayOfWeek KEYWORD2
getDayOfWeekString KEYWORD2
getHour KEYWORD2
getMin KEYWORD2
getSecond KEYWORD2
getNumberOfDayThisYear KEYWORD2
getTotalDays KEYWORD2
dayofWeek KEYWORD2
getCurrentSecond KEYWORD2
getCurrentTimestamp KEYWORD2
getTimeFromSec KEYWORD2
getDateTimeString KEYWORD2
copyMessages KEYWORD2
deleteMessages KEYWORD2
createFolder KEYWORD2
deleteFolder KEYWORD2
#######################################
# Struct (KEYWORD3)
#######################################
esp_mail_email_info_t KEYWORD3
esp_mail_plain_body_t KEYWORD3
esp_mail_html_body_t KEYWORD3
esp_mail_smtp_msg_response_t KEYWORD3
esp_mail_smtp_enable_option_t KEYWORD3
esp_mail_email_info_t KEYWORD3
esp_mail_folder_info_item_t KEYWORD3
esp_mail_sesson_sever_config_t KEYWORD3
esp_mail_sesson_login_config_t KEYWORD3
esp_mail_sesson_secure_config_t KEYWORD3
esp_mail_sesson_cert_config_t KEYWORD3
esp_mail_imap_fetch_config_t KEYWORD3
esp_mail_imap_search_config_t KEYWORD3
esp_mail_imap_limit_config_t KEYWORD3
esp_mail_imap_enable_config_t KEYWORD3
esp_mail_imap_download_config_t KEYWORD3
esp_mail_imap_storage_config_t KEYWORD3
esp_mail_file_storage_type_none KEYWORD3
esp_mail_file_storage_type_flash KEYWORD3
esp_mail_file_storage_type_sd KEYWORD3

View File

@ -1,16 +1,16 @@
{
"name": "ESP Mail Client",
"version": "1.2.0",
"keywords": "communication, email, imap, smtp, esp32, esp8266, arduino",
"description": "Mail Client Arduino Library for Espressif ESP32 and ESP8266 devices. This library allows the ESP32 and ESP8266 devices to send and read Email with the many options and features e.g. the attachments, inline images, embeded rfc822 messages are supported for upload when sending and download when reading the Emails.",
"repository": {
"type": "git",
"url": "https://github.com/mobizt/ESP-Mail-Client.git"
},
"authors": [{
"name": "Mobizt",
"email": "suwatchai@outlook.com"
}],
"frameworks": "arduino",
"platforms": "espressif32, espressif8266"
}
{
"name": "ESP Mail Client",
"version": "1.2.0",
"keywords": "communication, email, imap, smtp, esp32, esp8266, arduino",
"description": "Mail Client Arduino Library for Espressif ESP32 and ESP8266 devices. This library allows the ESP32 and ESP8266 devices to send and read Email with the many options and features e.g. the attachments, inline images, embeded rfc822 messages are supported for upload when sending and download when reading the Emails.",
"repository": {
"type": "git",
"url": "https://github.com/mobizt/ESP-Mail-Client.git"
},
"authors": [{
"name": "Mobizt",
"email": "suwatchai@outlook.com"
}],
"frameworks": "arduino",
"platforms": "espressif32, espressif8266"
}

View File

@ -1,17 +1,17 @@
name=ESP Mail Client
version=1.2.0
author=Mobizt
maintainer=Mobizt <suwatchai@outlook.com>
sentence=Mail Client Arduino Library for Espressif ESP32 and ESP8266 devices.
paragraph=This library allows the ESP32 and ESP8266 devices to send and read Email with the many options and features e.g. the attachments, inline images, embeded rfc822 messages are supported for upload when sending and download when reading the Emails.
category=Communication
url=https://github.com/mobizt/ESP-Mail-Client
architectures=esp32,esp8266
name=ESP Mail Client
version=1.2.0
author=Mobizt
maintainer=Mobizt <suwatchai@outlook.com>
sentence=Mail Client Arduino Library for Espressif ESP32 and ESP8266 devices.
paragraph=This library allows the ESP32 and ESP8266 devices to send and read Email with the many options and features e.g. the attachments, inline images, embeded rfc822 messages are supported for upload when sending and download when reading the Emails.
category=Communication
url=https://github.com/mobizt/ESP-Mail-Client
architectures=esp32,esp8266

View File

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 52 KiB

View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,286 +1,286 @@
/*
* ESP8266/ESP32 Internet Time Helper Arduino Library v 1.0.2
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ESPTimeHelper_CPP
#define ESPTimeHelper_CPP
#include "ESPTimeHelper.h"
ESPTimeHelper::ESPTimeHelper()
{
}
uint32_t ESPTimeHelper::getUnixTime()
{
uint32_t utime = (msec_time_diff + millis()) / 1000;
return utime;
}
int ESPTimeHelper::setTimestamp(time_t ts)
{
struct timeval tm = {ts, 0};//sec, us
return settimeofday((const timeval *)&tm, 0);
}
time_t ESPTimeHelper::getTimestamp(int year, int mon, int date, int hour, int mins, int sec)
{
struct tm timeinfo;
timeinfo.tm_year = year - 1900;
timeinfo.tm_mon = mon - 1;
timeinfo.tm_mday = date;
timeinfo.tm_hour = hour;
timeinfo.tm_min = mins;
timeinfo.tm_sec = sec;
time_t ts = mktime(&timeinfo);
return ts;
}
bool ESPTimeHelper::setClock(float gmtOffset, float daylightOffset)
{
TZ = gmtOffset;
DST_MN = daylightOffset;
configTime((TZ)*3600, (DST_MN)*60, "pool.ntp.org", "time.nist.gov");
now = time(nullptr);
uint8_t attempts = 0;
while (now < 1577836800)
{
now = time(nullptr);
attempts++;
if (attempts > 200 || now > 1577836800)
break;
delay(100);
}
uint64_t tmp = now;
tmp = tmp * 1000;
msec_time_diff = tmp - millis();
#if defined(ESP32)
getLocalTime(&timeinfo);
#elif defined(ESP8266)
gmtime_r(&now, &timeinfo);
#endif
clockReady = now > 8 * 3600 * 2;
return clockReady;
}
int ESPTimeHelper::getYear()
{
setSysTime();
return timeinfo.tm_year + 1900;
}
int ESPTimeHelper::getMonth()
{
setSysTime();
return timeinfo.tm_mon + 1;
}
int ESPTimeHelper::getDay()
{
setSysTime();
return timeinfo.tm_mday;
}
int ESPTimeHelper::getDayOfWeek()
{
setSysTime();
return timeinfo.tm_wday;
}
String ESPTimeHelper::getDayOfWeekString()
{
setSysTime();
return dow[timeinfo.tm_wday];
}
int ESPTimeHelper::getHour()
{
setSysTime();
return timeinfo.tm_hour;
}
int ESPTimeHelper::getMin()
{
setSysTime();
return timeinfo.tm_min;
}
int ESPTimeHelper::getSec()
{
setSysTime();
return timeinfo.tm_sec;
}
int ESPTimeHelper::getNumberOfDayThisYear()
{
setSysTime();
return timeinfo.tm_yday + 1;
}
int ESPTimeHelper::totalDays(int y, int m, int d)
{
static char daytab[2][13] =
{
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
int daystotal = d;
for (int year = 1; year <= y; year++)
{
int max_month = (year < y ? 12 : m - 1);
int leap = (year % 4 == 0);
if (year % 100 == 0 && year % 400 != 0)
leap = 0;
for (int month = 1; month <= max_month; month++)
{
daystotal += daytab[leap][month];
}
}
return daystotal;
}
int ESPTimeHelper::getTotalDays(int year, int month, int day)
{
return totalDays(year, month, day) - totalDays(1970, 1, 1);
}
int ESPTimeHelper::dayofWeek(int year, int month, int day) /* 1 <= m <= 12, y > 1752 (in the U.K.) */
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
year -= month < 3;
return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;
}
int ESPTimeHelper::getCurrentSecond()
{
return (timeinfo.tm_hour * 3600) + (timeinfo.tm_min * 60) + timeinfo.tm_sec;
}
uint64_t ESPTimeHelper::getCurrentTimestamp()
{
return now;
}
struct tm ESPTimeHelper::getTimeFromSec(int seconds)
{
struct tm timeinfo;
int _yrs = seconds / (365 * 24 * 3600);
seconds = seconds - _yrs * (365 * 24 * 3600);
timeinfo.tm_year = _yrs - 1900;
int _months = seconds / (30 * 24 * 3600);
seconds = seconds - _months * (30 * 24 * 3600);
timeinfo.tm_mon = _months - 1;
int _days = seconds / (24 * 3600);
seconds = seconds - _days * (24 * 3600);
timeinfo.tm_mday = _days;
int _hr = seconds / 3600;
seconds = seconds - _hr * 3600;
timeinfo.tm_hour = _hr;
int _min = seconds / 60;
seconds = seconds - _min * 60;
timeinfo.tm_min = _min;
timeinfo.tm_sec = seconds;
return timeinfo;
}
char *ESPTimeHelper::intStr(int value)
{
char *buf = new char[36];
memset(buf, 0, 36);
itoa(value, buf, 10);
return buf;
}
String ESPTimeHelper::getDateTimeString()
{
setSysTime();
std::string s;
s = sdow[timeinfo.tm_wday];
s += ", ";
char *tmp = intStr(timeinfo.tm_mday);
s += tmp;
delete[] tmp;
s += " ";
s += months[timeinfo.tm_mon];
s += " ";
tmp = intStr(timeinfo.tm_year + 1900);
s += tmp;
delete[] tmp;
s += " ";
if (timeinfo.tm_hour < 10)
s += "0";
tmp = intStr(timeinfo.tm_hour);
s += tmp;
delete[] tmp;
s += ":";
if (timeinfo.tm_min < 10)
s += "0";
tmp = intStr(timeinfo.tm_min);
s += tmp;
delete[] tmp;
s += ":";
if (timeinfo.tm_sec < 10)
s += "0";
tmp = intStr(timeinfo.tm_sec);
s += tmp;
delete[] tmp;
int p = 1;
if (TZ < 0)
p = -1;
int tz = TZ;
float dif = (p * (TZ - tz)) * 60.0;
if (TZ < 0)
s += " -";
else
s += " +";
if (tz < 10)
s += "0";
tmp = intStr(tz);
s += tmp;
delete[] tmp;
if (dif < 10)
s += "0";
tmp = intStr((int)dif);
s += tmp;
delete[] tmp;
return s.c_str();
}
void ESPTimeHelper::setSysTime()
{
#if defined(ESP32)
getLocalTime(&timeinfo);
#elif defined(ESP8266)
now = time(nullptr);
localtime_r(&now, &timeinfo);
#endif
}
/*
* ESP8266/ESP32 Internet Time Helper Arduino Library v 1.0.2
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ESPTimeHelper_CPP
#define ESPTimeHelper_CPP
#include "ESPTimeHelper.h"
ESPTimeHelper::ESPTimeHelper()
{
}
uint32_t ESPTimeHelper::getUnixTime()
{
uint32_t utime = (msec_time_diff + millis()) / 1000;
return utime;
}
int ESPTimeHelper::setTimestamp(time_t ts)
{
struct timeval tm = {ts, 0};//sec, us
return settimeofday((const timeval *)&tm, 0);
}
time_t ESPTimeHelper::getTimestamp(int year, int mon, int date, int hour, int mins, int sec)
{
struct tm timeinfo;
timeinfo.tm_year = year - 1900;
timeinfo.tm_mon = mon - 1;
timeinfo.tm_mday = date;
timeinfo.tm_hour = hour;
timeinfo.tm_min = mins;
timeinfo.tm_sec = sec;
time_t ts = mktime(&timeinfo);
return ts;
}
bool ESPTimeHelper::setClock(float gmtOffset, float daylightOffset)
{
TZ = gmtOffset;
DST_MN = daylightOffset;
configTime((TZ)*3600, (DST_MN)*60, "pool.ntp.org", "time.nist.gov");
now = time(nullptr);
uint8_t attempts = 0;
while (now < 1577836800)
{
now = time(nullptr);
attempts++;
if (attempts > 200 || now > 1577836800)
break;
delay(100);
}
uint64_t tmp = now;
tmp = tmp * 1000;
msec_time_diff = tmp - millis();
#if defined(ESP32)
getLocalTime(&timeinfo);
#elif defined(ESP8266)
gmtime_r(&now, &timeinfo);
#endif
clockReady = now > 8 * 3600 * 2;
return clockReady;
}
int ESPTimeHelper::getYear()
{
setSysTime();
return timeinfo.tm_year + 1900;
}
int ESPTimeHelper::getMonth()
{
setSysTime();
return timeinfo.tm_mon + 1;
}
int ESPTimeHelper::getDay()
{
setSysTime();
return timeinfo.tm_mday;
}
int ESPTimeHelper::getDayOfWeek()
{
setSysTime();
return timeinfo.tm_wday;
}
String ESPTimeHelper::getDayOfWeekString()
{
setSysTime();
return dow[timeinfo.tm_wday];
}
int ESPTimeHelper::getHour()
{
setSysTime();
return timeinfo.tm_hour;
}
int ESPTimeHelper::getMin()
{
setSysTime();
return timeinfo.tm_min;
}
int ESPTimeHelper::getSec()
{
setSysTime();
return timeinfo.tm_sec;
}
int ESPTimeHelper::getNumberOfDayThisYear()
{
setSysTime();
return timeinfo.tm_yday + 1;
}
int ESPTimeHelper::totalDays(int y, int m, int d)
{
static char daytab[2][13] =
{
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
int daystotal = d;
for (int year = 1; year <= y; year++)
{
int max_month = (year < y ? 12 : m - 1);
int leap = (year % 4 == 0);
if (year % 100 == 0 && year % 400 != 0)
leap = 0;
for (int month = 1; month <= max_month; month++)
{
daystotal += daytab[leap][month];
}
}
return daystotal;
}
int ESPTimeHelper::getTotalDays(int year, int month, int day)
{
return totalDays(year, month, day) - totalDays(1970, 1, 1);
}
int ESPTimeHelper::dayofWeek(int year, int month, int day) /* 1 <= m <= 12, y > 1752 (in the U.K.) */
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
year -= month < 3;
return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;
}
int ESPTimeHelper::getCurrentSecond()
{
return (timeinfo.tm_hour * 3600) + (timeinfo.tm_min * 60) + timeinfo.tm_sec;
}
uint64_t ESPTimeHelper::getCurrentTimestamp()
{
return now;
}
struct tm ESPTimeHelper::getTimeFromSec(int seconds)
{
struct tm timeinfo;
int _yrs = seconds / (365 * 24 * 3600);
seconds = seconds - _yrs * (365 * 24 * 3600);
timeinfo.tm_year = _yrs - 1900;
int _months = seconds / (30 * 24 * 3600);
seconds = seconds - _months * (30 * 24 * 3600);
timeinfo.tm_mon = _months - 1;
int _days = seconds / (24 * 3600);
seconds = seconds - _days * (24 * 3600);
timeinfo.tm_mday = _days;
int _hr = seconds / 3600;
seconds = seconds - _hr * 3600;
timeinfo.tm_hour = _hr;
int _min = seconds / 60;
seconds = seconds - _min * 60;
timeinfo.tm_min = _min;
timeinfo.tm_sec = seconds;
return timeinfo;
}
char *ESPTimeHelper::intStr(int value)
{
char *buf = new char[36];
memset(buf, 0, 36);
itoa(value, buf, 10);
return buf;
}
String ESPTimeHelper::getDateTimeString()
{
setSysTime();
std::string s;
s = sdow[timeinfo.tm_wday];
s += ", ";
char *tmp = intStr(timeinfo.tm_mday);
s += tmp;
delete[] tmp;
s += " ";
s += months[timeinfo.tm_mon];
s += " ";
tmp = intStr(timeinfo.tm_year + 1900);
s += tmp;
delete[] tmp;
s += " ";
if (timeinfo.tm_hour < 10)
s += "0";
tmp = intStr(timeinfo.tm_hour);
s += tmp;
delete[] tmp;
s += ":";
if (timeinfo.tm_min < 10)
s += "0";
tmp = intStr(timeinfo.tm_min);
s += tmp;
delete[] tmp;
s += ":";
if (timeinfo.tm_sec < 10)
s += "0";
tmp = intStr(timeinfo.tm_sec);
s += tmp;
delete[] tmp;
int p = 1;
if (TZ < 0)
p = -1;
int tz = TZ;
float dif = (p * (TZ - tz)) * 60.0;
if (TZ < 0)
s += " -";
else
s += " +";
if (tz < 10)
s += "0";
tmp = intStr(tz);
s += tmp;
delete[] tmp;
if (dif < 10)
s += "0";
tmp = intStr((int)dif);
s += tmp;
delete[] tmp;
return s.c_str();
}
void ESPTimeHelper::setSysTime()
{
#if defined(ESP32)
getLocalTime(&timeinfo);
#elif defined(ESP8266)
now = time(nullptr);
localtime_r(&now, &timeinfo);
#endif
}
#endif //ESPTimeHelper_CPP

View File

@ -1,199 +1,199 @@
/*
* ESP8266/ESP32 Internet Time Helper Arduino Library v 1.0.2
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ESPTimeHelper_H
#define ESPTimeHelper_H
#include <time.h>
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include "SDK_Version_Common.h"
#endif
class ESPTimeHelper
{
public:
ESPTimeHelper();
/** Set the system time from the NTP server
*
* @param gmtOffset The GMT time offset in hour.
* @param daylightOffset The Daylight time offset in hour.
* @return boolean The status indicates the success of operation.
*
* @note This requires internet connection
*/
bool setClock(float gmtOffset, float daylightOffset);
/** Set system time with provided timestamp
*
* @param ts timestamp in seconds from midnight Jan 1, 1970.
* @return error number, 0 for success.
*/
int setTimestamp(time_t ts);
/** Provide the Unix time
*
* @return uint32_t The value of current Unix time.
*/
uint32_t getUnixTime();
/** Provide the timestamp from the year, month, date, hour, minute,
* and second provided.
*
* @param year The year.
* @param mon The month from 1 to 12.
* @param date The dates.
* @param hour The hours.
* @param mins The minutes.
* @param sec The seconds.
* @return time_t The value of timestamp.
*/
time_t getTimestamp(int year, int mon, int date, int hour, int mins, int sec);
/** Provide the current year.
*
* @return int The value of current year.
*/
int getYear();
/** Provide the current month.
*
* @return int The value of current month.
*/
int getMonth();
/** Provide the current date.
*
* @return int The value of current date.
*/
int getDay();
/** Provide the current day of week.
*
* @return int The value of current day of week.
*
* @note 1 for sunday and 7 for saturday.
*/
int getDayOfWeek();
/** Provide the current day of week in String.
*
* @return String The value of day of week.
*/
String getDayOfWeekString();
/** Provide the current hour.
*
* @return int The value of current hour (0 to 23).
*/
int getHour();
/** Provide the current minute.
*
* @return int The value of current minute.
*/
int getMin();
/** Provide the current second.
*
* @return int The value of current second.
*/
int getSec();
/** Provide the total days of current year.
*
* @return int The value of total days of current year.
*/
int getNumberOfDayThisYear();
/** Provide the total days of from January 1, 1970 to specific date.
*
* @param year The year from 1970.
* @param mon The month from 1 to 12.
* @param day The dates.
* @return int The value of total days.
*/
int getTotalDays(int year, int month, int day);
/** Provide the day of week from specific date.
*
* @param year The year from 1970.
* @param mon The month from 1 to 12.
* @param day The dates.
* @return int the value of day of week.
* @note 1 for sunday and 7 for saturday
*/
int dayofWeek(int year, int month, int day);
/** Provide the second of current hour.
*
* @return int The value of current second.
*/
int getCurrentSecond();
/** Provide the current timestamp.
*
* @return uint64_t The value of current timestamp.
*/
uint64_t getCurrentTimestamp();
/** Provide the date and time from second counted from January 1, 1970.
*
* @param sec The seconds from January 1, 1970 00.00.
* @return tm The tm structured data.
*
* @note The returned structured data tm has the members e.g.
* tm_year (from 1900), tm_mon (from 0 to 11), tm_mday, tm_hour,
* tm_min and tm_sec.
*/
struct tm getTimeFromSec(int seconds);
/** Provide the current date time string that valid for Email.
*
* @return String The current date time string.
*/
String getDateTimeString();
time_t now;
uint64_t msec_time_diff = 0;
struct tm timeinfo;
float TZ = 0.0;
uint8_t DST_MN = 0;
bool clockReady = false;
private:
int totalDays(int y, int m, int d);
char *intStr(int value);
void setSysTime();
const char *dow[7] = {"sunday", "monday", "tuesday", "wednesday", "thurseday", "friday", "saturday"};
const char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
const char *sdow[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
};
#endif //ESPTimeHelper_H
/*
* ESP8266/ESP32 Internet Time Helper Arduino Library v 1.0.2
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ESPTimeHelper_H
#define ESPTimeHelper_H
#include <time.h>
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include "SDK_Version_Common.h"
#endif
class ESPTimeHelper
{
public:
ESPTimeHelper();
/** Set the system time from the NTP server
*
* @param gmtOffset The GMT time offset in hour.
* @param daylightOffset The Daylight time offset in hour.
* @return boolean The status indicates the success of operation.
*
* @note This requires internet connection
*/
bool setClock(float gmtOffset, float daylightOffset);
/** Set system time with provided timestamp
*
* @param ts timestamp in seconds from midnight Jan 1, 1970.
* @return error number, 0 for success.
*/
int setTimestamp(time_t ts);
/** Provide the Unix time
*
* @return uint32_t The value of current Unix time.
*/
uint32_t getUnixTime();
/** Provide the timestamp from the year, month, date, hour, minute,
* and second provided.
*
* @param year The year.
* @param mon The month from 1 to 12.
* @param date The dates.
* @param hour The hours.
* @param mins The minutes.
* @param sec The seconds.
* @return time_t The value of timestamp.
*/
time_t getTimestamp(int year, int mon, int date, int hour, int mins, int sec);
/** Provide the current year.
*
* @return int The value of current year.
*/
int getYear();
/** Provide the current month.
*
* @return int The value of current month.
*/
int getMonth();
/** Provide the current date.
*
* @return int The value of current date.
*/
int getDay();
/** Provide the current day of week.
*
* @return int The value of current day of week.
*
* @note 1 for sunday and 7 for saturday.
*/
int getDayOfWeek();
/** Provide the current day of week in String.
*
* @return String The value of day of week.
*/
String getDayOfWeekString();
/** Provide the current hour.
*
* @return int The value of current hour (0 to 23).
*/
int getHour();
/** Provide the current minute.
*
* @return int The value of current minute.
*/
int getMin();
/** Provide the current second.
*
* @return int The value of current second.
*/
int getSec();
/** Provide the total days of current year.
*
* @return int The value of total days of current year.
*/
int getNumberOfDayThisYear();
/** Provide the total days of from January 1, 1970 to specific date.
*
* @param year The year from 1970.
* @param mon The month from 1 to 12.
* @param day The dates.
* @return int The value of total days.
*/
int getTotalDays(int year, int month, int day);
/** Provide the day of week from specific date.
*
* @param year The year from 1970.
* @param mon The month from 1 to 12.
* @param day The dates.
* @return int the value of day of week.
* @note 1 for sunday and 7 for saturday
*/
int dayofWeek(int year, int month, int day);
/** Provide the second of current hour.
*
* @return int The value of current second.
*/
int getCurrentSecond();
/** Provide the current timestamp.
*
* @return uint64_t The value of current timestamp.
*/
uint64_t getCurrentTimestamp();
/** Provide the date and time from second counted from January 1, 1970.
*
* @param sec The seconds from January 1, 1970 00.00.
* @return tm The tm structured data.
*
* @note The returned structured data tm has the members e.g.
* tm_year (from 1900), tm_mon (from 0 to 11), tm_mday, tm_hour,
* tm_min and tm_sec.
*/
struct tm getTimeFromSec(int seconds);
/** Provide the current date time string that valid for Email.
*
* @return String The current date time string.
*/
String getDateTimeString();
time_t now;
uint64_t msec_time_diff = 0;
struct tm timeinfo;
float TZ = 0.0;
uint8_t DST_MN = 0;
bool clockReady = false;
private:
int totalDays(int y, int m, int d);
char *intStr(int value);
void setSysTime();
const char *dow[7] = {"sunday", "monday", "tuesday", "wednesday", "thurseday", "friday", "saturday"};
const char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
const char *sdow[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
};
#endif //ESPTimeHelper_H

View File

@ -1,65 +1,65 @@
#ifndef MIMEInfo_H
#define MIMEInfo_H
#include <Arduino.h>
enum esp_mail_file_extension
{
esp_mail_file_extension_html,
esp_mail_file_extension_htm,
esp_mail_file_extension_css,
esp_mail_file_extension_txt,
esp_mail_file_extension_js,
esp_mail_file_extension_json,
esp_mail_file_extension_png,
esp_mail_file_extension_gif,
esp_mail_file_extension_jpg,
esp_mail_file_extension_ico,
esp_mail_file_extension_svg,
esp_mail_file_extension_ttf,
esp_mail_file_extension_otf,
esp_mail_file_extension_woff,
esp_mail_file_extension_woff2,
esp_mail_file_extension_eot,
esp_mail_file_extension_sfnt,
esp_mail_file_extension_xml,
esp_mail_file_extension_pdf,
esp_mail_file_extension_zip,
esp_mail_file_extension_gz,
esp_mail_file_extension_appcache,
esp_mail_file_extension_none,
esp_mail_file_extension_maxType
};
struct esp_mail_mime_prop_t
{
char endsWith[10];
char mimeType[50];
};
const struct esp_mail_mime_prop_t mimeinfo[esp_mail_file_extension_maxType] PROGMEM =
{
{".html", "text/html"},
{".htm", "text/html"},
{".css", "text/css"},
{".txt", "text/plain"},
{".js", "application/javascript"},
{".json", "application/json"},
{".png", "image/png"},
{".gif", "image/gif"},
{".jpg", "image/jpeg"},
{".ico", "image/x-icon"},
{".svg", "image/svg+xml"},
{".ttf", "application/x-font-ttf"},
{".otf", "application/x-font-opentype"},
{".woff", "application/font-woff"},
{".woff2", "application/font-woff2"},
{".eot", "application/vnd.ms-fontobject"},
{".sfnt", "application/font-sfnt"},
{".xml", "text/xml"},
{".pdf", "application/pdf"},
{".zip", "application/zip"},
{".gz", "application/x-gzip"},
{".appcache", "text/cache-manifest"},
{"", "application/octet-stream"}};
#endif
#ifndef MIMEInfo_H
#define MIMEInfo_H
#include <Arduino.h>
enum esp_mail_file_extension
{
esp_mail_file_extension_html,
esp_mail_file_extension_htm,
esp_mail_file_extension_css,
esp_mail_file_extension_txt,
esp_mail_file_extension_js,
esp_mail_file_extension_json,
esp_mail_file_extension_png,
esp_mail_file_extension_gif,
esp_mail_file_extension_jpg,
esp_mail_file_extension_ico,
esp_mail_file_extension_svg,
esp_mail_file_extension_ttf,
esp_mail_file_extension_otf,
esp_mail_file_extension_woff,
esp_mail_file_extension_woff2,
esp_mail_file_extension_eot,
esp_mail_file_extension_sfnt,
esp_mail_file_extension_xml,
esp_mail_file_extension_pdf,
esp_mail_file_extension_zip,
esp_mail_file_extension_gz,
esp_mail_file_extension_appcache,
esp_mail_file_extension_none,
esp_mail_file_extension_maxType
};
struct esp_mail_mime_prop_t
{
char endsWith[10];
char mimeType[50];
};
const struct esp_mail_mime_prop_t mimeinfo[esp_mail_file_extension_maxType] PROGMEM =
{
{".html", "text/html"},
{".htm", "text/html"},
{".css", "text/css"},
{".txt", "text/plain"},
{".js", "application/javascript"},
{".json", "application/json"},
{".png", "image/png"},
{".gif", "image/gif"},
{".jpg", "image/jpeg"},
{".ico", "image/x-icon"},
{".svg", "image/svg+xml"},
{".ttf", "application/x-font-ttf"},
{".otf", "application/x-font-opentype"},
{".woff", "application/font-woff"},
{".woff2", "application/font-woff2"},
{".eot", "application/vnd.ms-fontobject"},
{".sfnt", "application/font-sfnt"},
{".xml", "text/xml"},
{".pdf", "application/pdf"},
{".zip", "application/zip"},
{".gz", "application/x-gzip"},
{".appcache", "text/cache-manifest"},
{"", "application/octet-stream"}};
#endif

View File

@ -1,233 +1,233 @@
/*
* Customized version of ESP32 HTTPClient Library.
*
* v 1.1.5
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
* HTTPClient Arduino library for ESP32
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the HTTPClient for Arduino.
* Port to ESP32 by Evandro Luis Copercini (2017),
* changed fingerprints to CA verification.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef ESP_Mail_HTTPClient32_CPP
#define ESP_Mail_HTTPClient32_CPP
#ifdef ESP32
#include "ESP_Mail_HTTPClient32.h"
ESP_Mail_HTTPClient32::ESP_Mail_HTTPClient32()
{
}
ESP_Mail_HTTPClient32::~ESP_Mail_HTTPClient32()
{
if (_wcs)
{
_wcs->stop();
_wcs.reset(nullptr);
_wcs.release();
}
std::string().swap(_host);
std::string().swap(_caCertFile);
}
bool ESP_Mail_HTTPClient32::begin(const char *host, uint16_t port)
{
_host = host;
_port = port;
return true;
}
bool ESP_Mail_HTTPClient32::connected()
{
if (_wcs)
{
if (_secured)
return _wcs->connected();
else
return _wcs->_ns_connected();
}
return false;
}
bool ESP_Mail_HTTPClient32::send(const char *header)
{
if (!connected())
return false;
if (_secured)
return (_wcs->write(header, strlen(header)) == strlen(header));
else
return (_wcs->_ns_write(header, strlen(header)) == strlen(header));
}
int ESP_Mail_HTTPClient32::send(const char *header, const char *payload)
{
size_t size = strlen(payload);
if (strlen(header) > 0)
{
if (!connect(_secured))
{
return ESP_MAIL_ERROR_HTTPC_ERROR_CONNECTION_REFUSED;
}
if (!send(header))
{
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_HEADER_FAILED;
}
}
if (size > 0)
{
if (_secured)
{
if (_wcs->write(&payload[0], size) != size)
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED;
}
else
{
if (_wcs->_ns_write(&payload[0], size) != size)
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED;
}
}
return 0;
}
WiFiClient *ESP_Mail_HTTPClient32::stream(void)
{
if (connected())
return _wcs.get();
return nullptr;
}
ESP_Mail_WCS32 *ESP_Mail_HTTPClient32::_stream(void)
{
if (connected())
return _wcs.get();
return nullptr;
}
size_t ESP_Mail_HTTPClient32::_ns_print(const char *buf)
{
size_t size = strlen(buf);
return _wcs->_ns_write(&buf[0], size);
}
size_t ESP_Mail_HTTPClient32::_ns_println(const char *buf)
{
size_t size = strlen(buf);
size_t wr = _wcs->_ns_write((const char *)&buf[0], size);
std::string s = "\r\n";
wr += _wcs->_ns_write(s.c_str(), s.length());
return wr;
}
bool ESP_Mail_HTTPClient32::connect(void)
{
return connect(false);
}
bool ESP_Mail_HTTPClient32::connect(bool secured)
{
_secured = secured;
if (connected())
{
if (_secured)
{
while (_wcs->available() > 0)
_wcs->read();
}
else
{
while (_wcs->_ns_available() > 0)
_wcs->_ns_read();
}
return true;
}
if (_debugCallback)
_wcs->setDebugCB(&_debugCallback);
_wcs->setSTARTTLS(!secured);
if (!_wcs->connect(_host.c_str(), _port))
return false;
return connected();
}
void ESP_Mail_HTTPClient32::setDebugCallback(DebugMsgCallback cb)
{
_debugCallback = std::move(cb);
}
void ESP_Mail_HTTPClient32::setCACert(const char *caCert)
{
_wcs->setCACert(caCert);
if (caCert)
_certType = 1;
else
{
setInsecure();
_certType = 0;
}
//_wcs->setNoDelay(true);
}
void ESP_Mail_HTTPClient32::setCertFile(const char *caCertFile, esp_mail_file_storage_type storageType)
{
if (strlen(caCertFile) > 0)
{
File f;
if (storageType == esp_mail_file_storage_type_flash)
{
ESP_MAIL_FLASH_FS.begin();
if (ESP_MAIL_FLASH_FS.exists(caCertFile))
f = ESP_MAIL_FLASH_FS.open(caCertFile, FILE_READ);
}
else if (storageType == esp_mail_file_storage_type_sd)
{
ESP_MAIL_SD_FS.begin();
if (ESP_MAIL_SD_FS.exists(caCertFile))
f = ESP_MAIL_SD_FS.open(caCertFile, FILE_READ);
}
if (f)
{
size_t len = f.size();
_wcs->loadCACert(f, len);
f.close();
}
_certType = 2;
}
//_wcs->setNoDelay(true);
}
void ESP_Mail_HTTPClient32::setInsecure()
{
_wcs->setInsecure();
}
#endif //ESP32
#endif //ESP_Mail_HTTPClient32_CPP
/*
* Customized version of ESP32 HTTPClient Library.
*
* v 1.1.5
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
* HTTPClient Arduino library for ESP32
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the HTTPClient for Arduino.
* Port to ESP32 by Evandro Luis Copercini (2017),
* changed fingerprints to CA verification.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef ESP_Mail_HTTPClient32_CPP
#define ESP_Mail_HTTPClient32_CPP
#ifdef ESP32
#include "ESP_Mail_HTTPClient32.h"
ESP_Mail_HTTPClient32::ESP_Mail_HTTPClient32()
{
}
ESP_Mail_HTTPClient32::~ESP_Mail_HTTPClient32()
{
if (_wcs)
{
_wcs->stop();
_wcs.reset(nullptr);
_wcs.release();
}
std::string().swap(_host);
std::string().swap(_caCertFile);
}
bool ESP_Mail_HTTPClient32::begin(const char *host, uint16_t port)
{
_host = host;
_port = port;
return true;
}
bool ESP_Mail_HTTPClient32::connected()
{
if (_wcs)
{
if (_secured)
return _wcs->connected();
else
return _wcs->_ns_connected();
}
return false;
}
bool ESP_Mail_HTTPClient32::send(const char *header)
{
if (!connected())
return false;
if (_secured)
return (_wcs->write(header, strlen(header)) == strlen(header));
else
return (_wcs->_ns_write(header, strlen(header)) == strlen(header));
}
int ESP_Mail_HTTPClient32::send(const char *header, const char *payload)
{
size_t size = strlen(payload);
if (strlen(header) > 0)
{
if (!connect(_secured))
{
return ESP_MAIL_ERROR_HTTPC_ERROR_CONNECTION_REFUSED;
}
if (!send(header))
{
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_HEADER_FAILED;
}
}
if (size > 0)
{
if (_secured)
{
if (_wcs->write(&payload[0], size) != size)
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED;
}
else
{
if (_wcs->_ns_write(&payload[0], size) != size)
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED;
}
}
return 0;
}
WiFiClient *ESP_Mail_HTTPClient32::stream(void)
{
if (connected())
return _wcs.get();
return nullptr;
}
ESP_Mail_WCS32 *ESP_Mail_HTTPClient32::_stream(void)
{
if (connected())
return _wcs.get();
return nullptr;
}
size_t ESP_Mail_HTTPClient32::_ns_print(const char *buf)
{
size_t size = strlen(buf);
return _wcs->_ns_write(&buf[0], size);
}
size_t ESP_Mail_HTTPClient32::_ns_println(const char *buf)
{
size_t size = strlen(buf);
size_t wr = _wcs->_ns_write((const char *)&buf[0], size);
std::string s = "\r\n";
wr += _wcs->_ns_write(s.c_str(), s.length());
return wr;
}
bool ESP_Mail_HTTPClient32::connect(void)
{
return connect(false);
}
bool ESP_Mail_HTTPClient32::connect(bool secured)
{
_secured = secured;
if (connected())
{
if (_secured)
{
while (_wcs->available() > 0)
_wcs->read();
}
else
{
while (_wcs->_ns_available() > 0)
_wcs->_ns_read();
}
return true;
}
if (_debugCallback)
_wcs->setDebugCB(&_debugCallback);
_wcs->setSTARTTLS(!secured);
if (!_wcs->connect(_host.c_str(), _port))
return false;
return connected();
}
void ESP_Mail_HTTPClient32::setDebugCallback(DebugMsgCallback cb)
{
_debugCallback = std::move(cb);
}
void ESP_Mail_HTTPClient32::setCACert(const char *caCert)
{
_wcs->setCACert(caCert);
if (caCert)
_certType = 1;
else
{
setInsecure();
_certType = 0;
}
//_wcs->setNoDelay(true);
}
void ESP_Mail_HTTPClient32::setCertFile(const char *caCertFile, esp_mail_file_storage_type storageType)
{
if (strlen(caCertFile) > 0)
{
File f;
if (storageType == esp_mail_file_storage_type_flash)
{
ESP_MAIL_FLASH_FS.begin();
if (ESP_MAIL_FLASH_FS.exists(caCertFile))
f = ESP_MAIL_FLASH_FS.open(caCertFile, FILE_READ);
}
else if (storageType == esp_mail_file_storage_type_sd)
{
ESP_MAIL_SD_FS.begin();
if (ESP_MAIL_SD_FS.exists(caCertFile))
f = ESP_MAIL_SD_FS.open(caCertFile, FILE_READ);
}
if (f)
{
size_t len = f.size();
_wcs->loadCACert(f, len);
f.close();
}
_certType = 2;
}
//_wcs->setNoDelay(true);
}
void ESP_Mail_HTTPClient32::setInsecure()
{
_wcs->setInsecure();
}
#endif //ESP32
#endif //ESP_Mail_HTTPClient32_CPP

View File

@ -1,142 +1,142 @@
/*
* Customized version of ESP32 HTTPClient Library.
*
* v 1.1.5
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
* HTTPClient Arduino library for ESP32
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the HTTPClient for Arduino.
* Port to ESP32 by Evandro Luis Copercini (2017),
* changed fingerprints to CA verification.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef ESP_Mail_HTTPClient32_H
#define ESP_Mail_HTTPClient32_H
#ifdef ESP32
#include <Arduino.h>
#include <WiFiClient.h>
#include <FS.h>
//#include <SPIFFS.h>
#include <SD.h>
#include "ESP_Mail_FS.h"
#include "ESP_Mail_WCS32.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#define ESP_MAIL_FLASH_FS ESP_Mail_DEFAULT_FLASH_FS
#define ESP_MAIL_SD_FS ESP_Mail_DEFAULT_SD_FS
#if __has_include(<WiFiEspAT.h>) || __has_include(<espduino.h>)
#error WiFi UART bridge was not supported.
#endif
#define ESP_MAIL_ERROR_HTTPC_ERROR_CONNECTION_REFUSED (-1)
#define ESP_MAIL_ERROR_HTTPC_ERROR_SEND_HEADER_FAILED (-2)
#define ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3)
#define ESP_MAIL_DEFAULT_TCP_TIMEOUT_SEC 30
enum esp_mail_file_storage_type
{
esp_mail_file_storage_type_none,
esp_mail_file_storage_type_flash,
esp_mail_file_storage_type_sd,
esp_mail_file_storage_type_univ
};
class ESP_Mail_HTTPClient32
{
public:
ESP_Mail_HTTPClient32();
~ESP_Mail_HTTPClient32();
/**
* Initialization of new http connection.
* \param host - Host name without protocols.
* \param port - Server's port.
* \return True as default.
* If no certificate string provided, use (const char*)NULL to CAcert param
*/
bool begin(const char *host, uint16_t port);
/**
* Check the http connection status.
* \return True if connected.
*/
bool connected();
/**
* Establish http connection if header provided and send it, send payload if provided.
* \param header - The header string (constant chars array).
* \param payload - The payload string (constant chars array), optional.
* \return http status code, Return zero if new http connection and header and/or payload sent
* with no error or no header and payload provided. If obly payload provided, no new http connection was established.
*/
int send(const char *header, const char *payload);
/**
* Send extra header without making new http connection (if send has been called)
* \param header - The header string (constant chars array).
* \return True if header sending success.
* Need to call send with header first.
*/
bool send(const char *header);
/**
* Get the WiFi client pointer.
* \return WiFi client pointer.
*/
WiFiClient *stream(void);
/**
* Set insecure mode
*/
void setInsecure();
ESP_Mail_WCS32 *_stream(void);
size_t _ns_print(const char *buf);
size_t _ns_println(const char *buf);
int tcpTimeout = 40000;
bool connect(void);
bool connect(bool secured);
void setCACert(const char *caCert);
void setCertFile(const char *caCertFile, esp_mail_file_storage_type storageType);
void setDebugCallback(DebugMsgCallback cb);
bool _secured = true;
int _certType = -1;
std::string _caCertFile = "";
esp_mail_file_storage_type _caCertFileStoreageType = esp_mail_file_storage_type::esp_mail_file_storage_type_none;
protected:
DebugMsgCallback _debugCallback = NULL;
std::unique_ptr<ESP_Mail_WCS32> _wcs = std::unique_ptr<ESP_Mail_WCS32>(new ESP_Mail_WCS32());
std::string _host = "";
uint16_t _port = 0;
};
#endif //ESP32
#endif //ESP_Mail_HTTPClient32_H
/*
* Customized version of ESP32 HTTPClient Library.
*
* v 1.1.5
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
* HTTPClient Arduino library for ESP32
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the HTTPClient for Arduino.
* Port to ESP32 by Evandro Luis Copercini (2017),
* changed fingerprints to CA verification.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef ESP_Mail_HTTPClient32_H
#define ESP_Mail_HTTPClient32_H
#ifdef ESP32
#include <Arduino.h>
#include <WiFiClient.h>
#include <FS.h>
//#include <SPIFFS.h>
#include <SD.h>
#include "ESP_Mail_FS.h"
#include "ESP_Mail_WCS32.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#define ESP_MAIL_FLASH_FS ESP_Mail_DEFAULT_FLASH_FS
#define ESP_MAIL_SD_FS ESP_Mail_DEFAULT_SD_FS
#if __has_include(<WiFiEspAT.h>) || __has_include(<espduino.h>)
#error WiFi UART bridge was not supported.
#endif
#define ESP_MAIL_ERROR_HTTPC_ERROR_CONNECTION_REFUSED (-1)
#define ESP_MAIL_ERROR_HTTPC_ERROR_SEND_HEADER_FAILED (-2)
#define ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3)
#define ESP_MAIL_DEFAULT_TCP_TIMEOUT_SEC 30
enum esp_mail_file_storage_type
{
esp_mail_file_storage_type_none,
esp_mail_file_storage_type_flash,
esp_mail_file_storage_type_sd,
esp_mail_file_storage_type_univ
};
class ESP_Mail_HTTPClient32
{
public:
ESP_Mail_HTTPClient32();
~ESP_Mail_HTTPClient32();
/**
* Initialization of new http connection.
* \param host - Host name without protocols.
* \param port - Server's port.
* \return True as default.
* If no certificate string provided, use (const char*)NULL to CAcert param
*/
bool begin(const char *host, uint16_t port);
/**
* Check the http connection status.
* \return True if connected.
*/
bool connected();
/**
* Establish http connection if header provided and send it, send payload if provided.
* \param header - The header string (constant chars array).
* \param payload - The payload string (constant chars array), optional.
* \return http status code, Return zero if new http connection and header and/or payload sent
* with no error or no header and payload provided. If obly payload provided, no new http connection was established.
*/
int send(const char *header, const char *payload);
/**
* Send extra header without making new http connection (if send has been called)
* \param header - The header string (constant chars array).
* \return True if header sending success.
* Need to call send with header first.
*/
bool send(const char *header);
/**
* Get the WiFi client pointer.
* \return WiFi client pointer.
*/
WiFiClient *stream(void);
/**
* Set insecure mode
*/
void setInsecure();
ESP_Mail_WCS32 *_stream(void);
size_t _ns_print(const char *buf);
size_t _ns_println(const char *buf);
int tcpTimeout = 40000;
bool connect(void);
bool connect(bool secured);
void setCACert(const char *caCert);
void setCertFile(const char *caCertFile, esp_mail_file_storage_type storageType);
void setDebugCallback(DebugMsgCallback cb);
bool _secured = true;
int _certType = -1;
std::string _caCertFile = "";
esp_mail_file_storage_type _caCertFileStoreageType = esp_mail_file_storage_type::esp_mail_file_storage_type_none;
protected:
DebugMsgCallback _debugCallback = NULL;
std::unique_ptr<ESP_Mail_WCS32> _wcs = std::unique_ptr<ESP_Mail_WCS32>(new ESP_Mail_WCS32());
std::string _host = "";
uint16_t _port = 0;
};
#endif //ESP32
#endif //ESP_Mail_HTTPClient32_H

View File

@ -1,261 +1,261 @@
/*
* HTTP Client for ESP8266 wrapper v1.0.3
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ESP_Mail_HTTPClient_CPP
#define ESP_Mail_HTTPClient_CPP
#ifdef ESP8266
#include "ESP_Mail_HTTPClient.h"
ESP_Mail_HTTPClient::ESP_Mail_HTTPClient()
{
}
ESP_Mail_HTTPClient::~ESP_Mail_HTTPClient()
{
if (_wcs)
{
_wcs->stop();
_wcs.reset(nullptr);
_wcs.release();
}
std::string().swap(_host);
std::string().swap(_caCertFile);
_cacert.reset(new char);
_cacert = nullptr;
}
bool ESP_Mail_HTTPClient::begin(const char *host, uint16_t port)
{
if (strcmp(_host.c_str(), host) != 0)
mflnChecked = false;
_host = host;
_port = port;
//probe for fragmentation support at the specified size
if (!mflnChecked)
{
fragmentable = _wcs->probeMaxFragmentLength(_host.c_str(), _port, chunkSize);
if (fragmentable)
{
_bsslRxSize = chunkSize;
_bsslTxSize = chunkSize;
_wcs->setBufferSizes(_bsslRxSize, _bsslTxSize);
}
mflnChecked = true;
}
if (!fragmentable)
_wcs->setBufferSizes(maxRXBufSize / rxBufDivider, maxTXBufSize / txBufDivider);
return true;
}
bool ESP_Mail_HTTPClient::connected()
{
if (_wcs)
{
if (_secured)
return _wcs->connected();
else
return _wcs->_ns_connected();
}
return false;
}
bool ESP_Mail_HTTPClient::send(const char *header)
{
if (!connected())
return false;
if (_secured)
return (_wcs->write((uint8_t *)header, strlen(header)) == strlen(header));
else
return (_wcs->_ns_write((uint8_t *)header, strlen(header)) == strlen(header));
}
int ESP_Mail_HTTPClient::send(const char *header, const char *payload)
{
size_t size = strlen(payload);
if (strlen(header) > 0)
{
if (!connect(_secured))
{
return ESP_MAIL_ERROR_HTTPC_ERROR_CONNECTION_REFUSED;
}
if (!send(header))
{
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_HEADER_FAILED;
}
}
if (size > 0)
{
if (_secured)
{
if (_wcs->write((uint8_t *)&payload[0], size) != size)
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED;
}
else
{
if (_wcs->_ns_write((uint8_t *)&payload[0], size) != size)
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED;
}
}
return 0;
}
WiFiClient *ESP_Mail_HTTPClient::stream(void)
{
if (connected())
return _wcs.get();
return nullptr;
}
ESP_Mail::ESP_Mail_WCS *ESP_Mail_HTTPClient::_stream(void)
{
if (connected())
return _wcs.get();
return nullptr;
}
size_t ESP_Mail_HTTPClient::_ns_print(const char *buf)
{
size_t size = strlen(buf);
return _wcs->_ns_write((uint8_t *)&buf[0], size);
}
size_t ESP_Mail_HTTPClient::_ns_println(const char *buf)
{
size_t size = strlen(buf);
size_t wr = _wcs->_ns_write((uint8_t *)&buf[0], size);
std::string s = "\r\n";
wr += _wcs->_ns_write((uint8_t *)s.c_str(), s.length());
return wr;
}
bool ESP_Mail_HTTPClient::connect(bool secured)
{
_secured = secured;
if (connected())
{
if (_secured)
{
while (_wcs->available() > 0)
_wcs->read();
}
else
{
while (_wcs->_ns_available() > 0)
_wcs->_ns_read();
}
return true;
}
_wcs->setStartTLS(!_secured);
if (!_wcs->connect(_host.c_str(), _port))
return false;
return connected();
}
void ESP_Mail_HTTPClient::setCACert(const char *caCert)
{
#ifndef USING_AXTLS
_wcs->setBufferSizes(_bsslRxSize, _bsslTxSize);
#endif
if (caCert)
{
#ifndef USING_AXTLS
_wcs->setTrustAnchors(new ESP_Mail::ESP_Mail_X509List(caCert));
#else
_wcs->setCACert_P(caCert, strlen_P(caCert));
#endif
_certType = 1;
}
else
{
#ifndef USING_AXTLS
_wcs->setInsecure();
#endif
_certType = 0;
}
_wcs->setNoDelay(true);
}
void ESP_Mail_HTTPClient::setCertFile(const char *caCertFile, esp_mail_file_storage_type storageType, uint8_t sdPin)
{
#ifndef USING_AXTLS
_sdPin = sdPin;
_wcs->setBufferSizes(_bsslRxSize, _bsslTxSize);
if (_clockReady && strlen(caCertFile) > 0)
{
fs::File f;
if (storageType == esp_mail_file_storage_type_flash)
{
ESP_MAIL_FLASH_FS.begin();
if (ESP_MAIL_FLASH_FS.exists(caCertFile))
f = ESP_MAIL_FLASH_FS.open(caCertFile, "r");
}
else if (storageType == esp_mail_file_storage_type_sd)
{
ESP_MAIL_SD_FS.begin(_sdPin);
if (ESP_MAIL_SD_FS.exists(caCertFile))
f = ESP_MAIL_SD_FS.open(caCertFile, FILE_READ);
}
if (f)
{
size_t len = f.size();
uint8_t *der = new uint8_t[len];
if (f.available())
f.read(der, len);
f.close();
_wcs->setTrustAnchors(new ESP_Mail::ESP_Mail_X509List(der, len));
delete[] der;
}
_certType = 2;
}
#endif
_wcs->setNoDelay(true);
}
#endif /* ESP8266 */
/*
* HTTP Client for ESP8266 wrapper v1.0.3
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ESP_Mail_HTTPClient_CPP
#define ESP_Mail_HTTPClient_CPP
#ifdef ESP8266
#include "ESP_Mail_HTTPClient.h"
ESP_Mail_HTTPClient::ESP_Mail_HTTPClient()
{
}
ESP_Mail_HTTPClient::~ESP_Mail_HTTPClient()
{
if (_wcs)
{
_wcs->stop();
_wcs.reset(nullptr);
_wcs.release();
}
std::string().swap(_host);
std::string().swap(_caCertFile);
_cacert.reset(new char);
_cacert = nullptr;
}
bool ESP_Mail_HTTPClient::begin(const char *host, uint16_t port)
{
if (strcmp(_host.c_str(), host) != 0)
mflnChecked = false;
_host = host;
_port = port;
//probe for fragmentation support at the specified size
if (!mflnChecked)
{
fragmentable = _wcs->probeMaxFragmentLength(_host.c_str(), _port, chunkSize);
if (fragmentable)
{
_bsslRxSize = chunkSize;
_bsslTxSize = chunkSize;
_wcs->setBufferSizes(_bsslRxSize, _bsslTxSize);
}
mflnChecked = true;
}
if (!fragmentable)
_wcs->setBufferSizes(maxRXBufSize / rxBufDivider, maxTXBufSize / txBufDivider);
return true;
}
bool ESP_Mail_HTTPClient::connected()
{
if (_wcs)
{
if (_secured)
return _wcs->connected();
else
return _wcs->_ns_connected();
}
return false;
}
bool ESP_Mail_HTTPClient::send(const char *header)
{
if (!connected())
return false;
if (_secured)
return (_wcs->write((uint8_t *)header, strlen(header)) == strlen(header));
else
return (_wcs->_ns_write((uint8_t *)header, strlen(header)) == strlen(header));
}
int ESP_Mail_HTTPClient::send(const char *header, const char *payload)
{
size_t size = strlen(payload);
if (strlen(header) > 0)
{
if (!connect(_secured))
{
return ESP_MAIL_ERROR_HTTPC_ERROR_CONNECTION_REFUSED;
}
if (!send(header))
{
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_HEADER_FAILED;
}
}
if (size > 0)
{
if (_secured)
{
if (_wcs->write((uint8_t *)&payload[0], size) != size)
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED;
}
else
{
if (_wcs->_ns_write((uint8_t *)&payload[0], size) != size)
return ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED;
}
}
return 0;
}
WiFiClient *ESP_Mail_HTTPClient::stream(void)
{
if (connected())
return _wcs.get();
return nullptr;
}
ESP_Mail::ESP_Mail_WCS *ESP_Mail_HTTPClient::_stream(void)
{
if (connected())
return _wcs.get();
return nullptr;
}
size_t ESP_Mail_HTTPClient::_ns_print(const char *buf)
{
size_t size = strlen(buf);
return _wcs->_ns_write((uint8_t *)&buf[0], size);
}
size_t ESP_Mail_HTTPClient::_ns_println(const char *buf)
{
size_t size = strlen(buf);
size_t wr = _wcs->_ns_write((uint8_t *)&buf[0], size);
std::string s = "\r\n";
wr += _wcs->_ns_write((uint8_t *)s.c_str(), s.length());
return wr;
}
bool ESP_Mail_HTTPClient::connect(bool secured)
{
_secured = secured;
if (connected())
{
if (_secured)
{
while (_wcs->available() > 0)
_wcs->read();
}
else
{
while (_wcs->_ns_available() > 0)
_wcs->_ns_read();
}
return true;
}
_wcs->setStartTLS(!_secured);
if (!_wcs->connect(_host.c_str(), _port))
return false;
return connected();
}
void ESP_Mail_HTTPClient::setCACert(const char *caCert)
{
#ifndef USING_AXTLS
_wcs->setBufferSizes(_bsslRxSize, _bsslTxSize);
#endif
if (caCert)
{
#ifndef USING_AXTLS
_wcs->setTrustAnchors(new ESP_Mail::ESP_Mail_X509List(caCert));
#else
_wcs->setCACert_P(caCert, strlen_P(caCert));
#endif
_certType = 1;
}
else
{
#ifndef USING_AXTLS
_wcs->setInsecure();
#endif
_certType = 0;
}
_wcs->setNoDelay(true);
}
void ESP_Mail_HTTPClient::setCertFile(const char *caCertFile, esp_mail_file_storage_type storageType, uint8_t sdPin)
{
#ifndef USING_AXTLS
_sdPin = sdPin;
_wcs->setBufferSizes(_bsslRxSize, _bsslTxSize);
if (_clockReady && strlen(caCertFile) > 0)
{
fs::File f;
if (storageType == esp_mail_file_storage_type_flash)
{
ESP_MAIL_FLASH_FS.begin();
if (ESP_MAIL_FLASH_FS.exists(caCertFile))
f = ESP_MAIL_FLASH_FS.open(caCertFile, "r");
}
else if (storageType == esp_mail_file_storage_type_sd)
{
ESP_MAIL_SD_FS.begin(_sdPin);
if (ESP_MAIL_SD_FS.exists(caCertFile))
f = ESP_MAIL_SD_FS.open(caCertFile, FILE_READ);
}
if (f)
{
size_t len = f.size();
uint8_t *der = new uint8_t[len];
if (f.available())
f.read(der, len);
f.close();
_wcs->setTrustAnchors(new ESP_Mail::ESP_Mail_X509List(der, len));
delete[] der;
}
_certType = 2;
}
#endif
_wcs->setNoDelay(true);
}
#endif /* ESP8266 */
#endif /* ESP_Mail_HTTPClient_CPP */

View File

@ -1,149 +1,149 @@
/*
* HTTP Client for ESP8266 wrapper v1.0.3
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ESP_Mail_HTTPClient_H
#define ESP_Mail_HTTPClient_H
#ifdef ESP8266
//ARDUINO_ESP8266_GIT_VER
//2.6.2 0xbc204a9b
//2.6.1 0x482516e3
//2.6.0 0x643ec203
//2.5.2 0x8b899c12
//2.5.1 0xac02aff5
//2.5.0 0x951aeffa
//2.5.0-beta3 0x21db8fc9
//2.5.0-beta2 0x0fd86a07
//2.5.0-beta1 0x9c1e03a1
//2.4.2 0xbb28d4a3
//2.4.1 0x614f7c32
//2.4.0 0x4ceabea9
//2.4.0-rc2 0x0c897c37
//2.4.0-rc1 0xf6d232f1
#include <Arduino.h>
#include <core_version.h>
#include <time.h>
#include <string>
#include "SDK_Version_Common.h"
#ifndef ARDUINO_ESP8266_GIT_VER
#error Your ESP8266 Arduino Core SDK is outdated, please update. From Arduino IDE go to Boards Manager and search 'esp8266' then select the latest version.
#endif
#include <WiFiClient.h>
#if ARDUINO_ESP8266_GIT_VER != 0xf6d232f1 && ARDUINO_ESP8266_GIT_VER != 0x0c897c37 && ARDUINO_ESP8266_GIT_VER != 0x4ceabea9 && ARDUINO_ESP8266_GIT_VER != 0x614f7c32 && ARDUINO_ESP8266_GIT_VER != 0xbb28d4a3
#include "ESP_Mail_WCS.h"
#include "ESP_Mail_BearSSLHelpers.h"
#define ESP_MAIL_SSL_CLIENT ESP_Mail::ESP_Mail_WCS
#else
#error Please update the ESP8266 Arduino Core SDK to latest version.
#endif
#define FS_NO_GLOBALS
#include <FS.h>
#include <SD.h>
#include "ESP_Mail_FS.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#define ESP_MAIL_FLASH_FS ESP_Mail_DEFAULT_FLASH_FS
#define ESP_MAIL_SD_FS ESP_Mail_DEFAULT_SD_FS
#if __has_include(<WiFiEspAT.h>) || __has_include(<espduino.h>)
#error WiFi UART bridge was not supported.
#endif
#define ESP_MAIL_ERROR_HTTPC_ERROR_CONNECTION_REFUSED (-1)
#define ESP_MAIL_ERROR_HTTPC_ERROR_SEND_HEADER_FAILED (-2)
#define ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3)
#define ESP_MAIL_DEFAULT_TCP_TIMEOUT_SEC 30
enum esp_mail_file_storage_type
{
esp_mail_file_storage_type_none,
esp_mail_file_storage_type_flash,
esp_mail_file_storage_type_sd,
esp_mail_file_storage_type_univ
};
class ESP_Mail_HTTPClient
{
public:
ESP_Mail_HTTPClient();
~ESP_Mail_HTTPClient();
bool begin(const char *host, uint16_t port);
bool connected(void);
int send(const char *header, const char *payload);
bool send(const char *header);
WiFiClient *stream(void);
ESP_Mail::ESP_Mail_WCS *_stream(void);
size_t _ns_print(const char *buf);
size_t _ns_println(const char *buf);
void setCACert(const char *caCert);
void setCertFile(const char *caCertFile, esp_mail_file_storage_type storageType, uint8_t sdPin);
bool connect(bool secured);
int _certType = -1;
std::string _caCertFile = "";
esp_mail_file_storage_type _caCertFileStoreageType = esp_mail_file_storage_type::esp_mail_file_storage_type_none;
uint16_t tcpTimeout = 40000;
uint8_t _sdPin = 15;
bool _clockReady = false;
uint16_t _bsslRxSize = 1024;
uint16_t _bsslTxSize = 1024;
bool fragmentable = false;
int chunkSize = 1024;
int maxRXBufSize = 16384; //SSL full supported 16 kB
int maxTXBufSize = 16384;
bool mflnChecked = false;
int rxBufDivider = maxRXBufSize / chunkSize;
int txBufDivider = maxRXBufSize / chunkSize;
;
private:
std::unique_ptr<ESP_MAIL_SSL_CLIENT> _wcs = std::unique_ptr<ESP_MAIL_SSL_CLIENT>(new ESP_MAIL_SSL_CLIENT());
std::unique_ptr<char> _cacert;
std::string _host = "";
uint16_t _port = 0;
bool _secured = true;
};
#endif /* ESP8266 */
/*
* HTTP Client for ESP8266 wrapper v1.0.3
*
* The MIT License (MIT)
* Copyright (c) 2021 K. Suwatchai (Mobizt)
*
*
* Permission is hereby granted, free of charge, to any person returning a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ESP_Mail_HTTPClient_H
#define ESP_Mail_HTTPClient_H
#ifdef ESP8266
//ARDUINO_ESP8266_GIT_VER
//2.6.2 0xbc204a9b
//2.6.1 0x482516e3
//2.6.0 0x643ec203
//2.5.2 0x8b899c12
//2.5.1 0xac02aff5
//2.5.0 0x951aeffa
//2.5.0-beta3 0x21db8fc9
//2.5.0-beta2 0x0fd86a07
//2.5.0-beta1 0x9c1e03a1
//2.4.2 0xbb28d4a3
//2.4.1 0x614f7c32
//2.4.0 0x4ceabea9
//2.4.0-rc2 0x0c897c37
//2.4.0-rc1 0xf6d232f1
#include <Arduino.h>
#include <core_version.h>
#include <time.h>
#include <string>
#include "SDK_Version_Common.h"
#ifndef ARDUINO_ESP8266_GIT_VER
#error Your ESP8266 Arduino Core SDK is outdated, please update. From Arduino IDE go to Boards Manager and search 'esp8266' then select the latest version.
#endif
#include <WiFiClient.h>
#if ARDUINO_ESP8266_GIT_VER != 0xf6d232f1 && ARDUINO_ESP8266_GIT_VER != 0x0c897c37 && ARDUINO_ESP8266_GIT_VER != 0x4ceabea9 && ARDUINO_ESP8266_GIT_VER != 0x614f7c32 && ARDUINO_ESP8266_GIT_VER != 0xbb28d4a3
#include "ESP_Mail_WCS.h"
#include "ESP_Mail_BearSSLHelpers.h"
#define ESP_MAIL_SSL_CLIENT ESP_Mail::ESP_Mail_WCS
#else
#error Please update the ESP8266 Arduino Core SDK to latest version.
#endif
#define FS_NO_GLOBALS
#include <FS.h>
#include <SD.h>
#include "ESP_Mail_FS.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#define ESP_MAIL_FLASH_FS ESP_Mail_DEFAULT_FLASH_FS
#define ESP_MAIL_SD_FS ESP_Mail_DEFAULT_SD_FS
#if __has_include(<WiFiEspAT.h>) || __has_include(<espduino.h>)
#error WiFi UART bridge was not supported.
#endif
#define ESP_MAIL_ERROR_HTTPC_ERROR_CONNECTION_REFUSED (-1)
#define ESP_MAIL_ERROR_HTTPC_ERROR_SEND_HEADER_FAILED (-2)
#define ESP_MAIL_ERROR_HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3)
#define ESP_MAIL_DEFAULT_TCP_TIMEOUT_SEC 30
enum esp_mail_file_storage_type
{
esp_mail_file_storage_type_none,
esp_mail_file_storage_type_flash,
esp_mail_file_storage_type_sd,
esp_mail_file_storage_type_univ
};
class ESP_Mail_HTTPClient
{
public:
ESP_Mail_HTTPClient();
~ESP_Mail_HTTPClient();
bool begin(const char *host, uint16_t port);
bool connected(void);
int send(const char *header, const char *payload);
bool send(const char *header);
WiFiClient *stream(void);
ESP_Mail::ESP_Mail_WCS *_stream(void);
size_t _ns_print(const char *buf);
size_t _ns_println(const char *buf);
void setCACert(const char *caCert);
void setCertFile(const char *caCertFile, esp_mail_file_storage_type storageType, uint8_t sdPin);
bool connect(bool secured);
int _certType = -1;
std::string _caCertFile = "";
esp_mail_file_storage_type _caCertFileStoreageType = esp_mail_file_storage_type::esp_mail_file_storage_type_none;
uint16_t tcpTimeout = 40000;
uint8_t _sdPin = 15;
bool _clockReady = false;
uint16_t _bsslRxSize = 1024;
uint16_t _bsslTxSize = 1024;
bool fragmentable = false;
int chunkSize = 1024;
int maxRXBufSize = 16384; //SSL full supported 16 kB
int maxTXBufSize = 16384;
bool mflnChecked = false;
int rxBufDivider = maxRXBufSize / chunkSize;
int txBufDivider = maxRXBufSize / chunkSize;
;
private:
std::unique_ptr<ESP_MAIL_SSL_CLIENT> _wcs = std::unique_ptr<ESP_MAIL_SSL_CLIENT>(new ESP_MAIL_SSL_CLIENT());
std::unique_ptr<char> _cacert;
std::string _host = "";
uint16_t _port = 0;
bool _secured = true;
};
#endif /* ESP8266 */
#endif /* ESP_Mail_HTTPClient_H */

View File

@ -77,7 +77,7 @@ board = esp32-odroid
[env:tasmota32-core2]
extends = env:tasmota32-lvgl
board = esp32-m5core2
build_flags = ${env:tasmota32-lvgl.build_flags} -DUSE_I2S_SAY_TIME -DUSE_I2S_WEBRADIO -DUSE_SENDMAIL -DUSE_ESP32MAIL
build_flags = ${env:tasmota32-lvgl.build_flags} -DUSE_I2S_SAY_TIME -DUSE_I2S_WEBRADIO -DUSE_SENDMAIL
lib_extra_dirs = lib/libesp32, lib/libesp32_lvgl, lib/lib_basic, lib/lib_i2c, lib/lib_rf, lib/lib_div, lib/lib_ssl, lib/lib_display, lib/lib_audio
[env:tasmota32-bluetooth]

View File

@ -1,32 +0,0 @@
#ifndef __SENDEMAIL_H
#define __SENDEMAIL_H
//#define DEBUG_EMAIL_PORT
#include <base64.h>
#include "WiFiClientSecureLightBearSSL.h"
class SendEmail
{
private:
const String host;
const int port;
const String user;
const String passwd;
const int timeout;
const bool ssl;
const int auth_used;
// use bear ssl
BearSSL::WiFiClientSecure_light *client;
String readClient();
void a3_to_a4(unsigned char * a4, unsigned char * a3);
int base64_encode(char *output, const char *input, int inputLen);
public:
SendEmail(const String& host, const int port, const String& user, const String& passwd, const int timeout, const int auth_used);
bool send(const String& from, const String& to, const String& subject, const char *msg);
void send_message_txt(char *msg);
~SendEmail() {client->stop(); delete client;}
};
#endif

View File

@ -1129,7 +1129,15 @@
\*********************************************************************************************/
#ifdef USE_CONFIG_OVERRIDE
#include "user_config_override.h" // Configuration overrides for my_user_config.h
#include "user_config_override.h" // Configuration overrides for my_user_config.h
#endif
/*********************************************************************************************\
* Post-process obsoletes
\*********************************************************************************************/
#ifdef USE_ESP32MAIL
#define USE_SENDMAIL // USE_ESP32MAIL is replaced by USE_SENDMAIL
#endif
/*********************************************************************************************\
@ -1168,8 +1176,14 @@
* Post-process compile options for TLS
\*********************************************************************************************/
#if defined(USE_MQTT_TLS) || defined(USE_SENDMAIL) || defined(USE_TELEGRAM) || defined(USE_WEBCLIENT_HTTPS) || defined(USE_ALEXA_AVS)
#define USE_TLS // flag indicates we need to include TLS code
#ifdef ESP8266
#ifdef USE_SENDMAIL
#define USE_TLS // flag indicates we need to include TLS code
#endif
#endif
#if defined(USE_MQTT_TLS) || defined(USE_TELEGRAM) || defined(USE_WEBCLIENT_HTTPS) || defined(USE_ALEXA_AVS)
#define USE_TLS // flag indicates we need to include TLS code
#endif
/*********************************************************************************************\

View File

@ -1,26 +1,62 @@
/*
xdrv_01_1_webserver_mail.ino - Mail client
SPDX-FileCopyrightText: 2019 Gerhard Mutz and Theo Arends
SPDX-License-Identifier: GPL-3.0-only
*/
#ifdef ESP8266
#ifdef USE_WEBSERVER
#ifdef USE_SENDMAIL
#include "include/sendemail_ESP8266.h"
/*********************************************************************************************\
* ESP8266 SendMail works only with server port 465 SSL and doesnt support STARTTLS (not supported in Arduino)
* only a couple of mailservers support this (e.g. gmail,gmx,yahoo,freenetmail)
*
* sendmail [server:port:user:passwd:<from>:<to>:subject] body
*
* sendmail [*:*:*:*:*:to:subject] data uses defines from user_config_overwrite
* #define EMAIL_USER "user"
* #define EMAIL_PASSWORD "passwd"
* #define EMAIL_FROM "<mr.x@gmail.com>"
* #define EMAIL_SERVER "smtp.gmail.com"
* #define EMAIL_PORT 465
*
* if email body consist of a single * and scripter is present
* and a section >m is found, the lines in this section (until #) are sent as email body
*
* sendmail works with pre2.6 using Light BearSSL
* HW Watchdog 8.44 sec.
* SW Watchdog 3.2 sec.
\*********************************************************************************************/
// enable serial debugging
//#define DEBUG_EMAIL_PORT
//#define DEBUG_EMAIL_PORT // Enable serial debugging
// sendmail works only with server port 465 SSL and doesnt support STARTTLS (not supported in Arduino)
// only a couple of mailservers support this (e.g. gmail,gmx,yahoo,freenetmail)
// sendmail [server:port:user:passwd:from:to:subject] body
// sendmail [*:*:*:*:*:to:subject] data uses defines from user_config_overwrite
// #define EMAIL_USER "user"
// #define EMAIL_PASSWORD "passwd"
// #define EMAIL_FROM "<mr.x@gmail.com>"
// #define EMAIL_SERVER "smtp.gmail.com"
// #define EMAIL_PORT 465
// if email body consist of a single * and scripter is present
// and a section >m is found, the lines in this section (until #) are sent
// as email body
#include <base64.h>
#include "WiFiClientSecureLightBearSSL.h"
// sendmail works with pre2.6 using Light BearSSL
//HW Watchdog 8.44 sec.
//SW Watchdog 3.2 sec.
class SendEmail
{
private:
const String host;
const int port;
const String user;
const String passwd;
const int timeout;
const bool ssl;
const int auth_used;
// use bear ssl
BearSSL::WiFiClientSecure_light *client;
String readClient();
void a3_to_a4(unsigned char * a4, unsigned char * a3);
int base64_encode(char *output, const char *input, int inputLen);
public:
SendEmail(const String& host, const int port, const String& user, const String& passwd, const int timeout, const int auth_used);
bool send(const String& from, const String& to, const String& subject, const char *msg);
void send_message_txt(char *msg);
~SendEmail() {client->stop(); delete client;}
};
#ifndef SEND_MAIL_MINRAM
#define SEND_MAIL_MINRAM 12*1024
@ -142,7 +178,7 @@ uint16_t SendMail(char *buffer) {
if (*mserv=='*') {
mserv=xPSTR(EMAIL_SERVER);
}
#endif //USE_SENDMAIL
#endif
#ifdef DEBUG_EMAIL_PORT
@ -352,7 +388,7 @@ String buffer;
g_client=client;
script_send_email_body(xsend_message_txt);
} else {
#endif
#endif // USE_SCRIPT
buffer = F("\r\n");
client->print(buffer);
client->println(msg);
@ -396,7 +432,7 @@ void xsend_message_txt(char *msg) {
g_client->println(msg);
g_client->print(F("\r\n--frontier\r\n"));
}
#else
#else // No USE_UFILESYS
if (*msg=='&') {
msg++;
attach_Array(msg);
@ -406,7 +442,7 @@ void xsend_message_txt(char *msg) {
g_client->println(msg);
g_client->print(F("\r\n--frontier\r\n"));
}
#endif
#endif // USE_UFILESYS
}
float *get_array_by_name(char *name, uint16_t *alen);
@ -447,7 +483,7 @@ void attach_Array(char *aname) {
}
g_client->print(F("\r\n--frontier\r\n"));
}
#endif
#endif // USE_SCRIPT
#ifdef USE_UFILESYS
@ -481,9 +517,8 @@ void attach_File(char *path) {
g_client->print(F("\r\n--frontier\r\n"));
}
#endif // USE_UFILESYS
#endif // USE_UFILESYS
#endif // USE_SENDMAIL
#endif // ESP8266
#endif // USE_SENDMAIL
#endif // USE_WEBSERVER
#endif // ESP8266

View File

@ -1,14 +1,39 @@
#ifdef USE_ESP32MAIL
/*
xdrv_01_2_webserver_esp32_mail.ino - Mail client
SPDX-FileCopyrightText: 2020 Gerhard Mutz and Theo Arends
SPDX-License-Identifier: GPL-3.0-only
*/
#ifdef ESP32
#ifdef USE_WEBSERVER
#ifdef USE_SENDMAIL
/*********************************************************************************************\
* ESP32 SendMail works with server port 465 SSL and 587 STARTTLS
*
* sendmail [server:port:user:passwd:from:to:subject] body
*
* sendmail [*:*:*:*:*:to:subject] data uses defines from user_config_overwrite
* #define EMAIL_USER "user"
* #define EMAIL_PASSWORD "passwd"
* #define EMAIL_FROM "mr.x@gmail.com"
* #define EMAIL_SERVER "smtp.gmail.com"
* #define EMAIL_PORT 465
*
* if email body consist of a single * and scripter is present
* and a section >m is found, the lines in this section (until #) are sent as email body
\*********************************************************************************************/
#include <ESP_Mail_Client.h>
//#define DEBUG_EMAIL_PORT // Enable serial debugging
#ifndef SEND_MAIL32_MINRAM
#undef SEND_MAIL32_MINRAM
#define SEND_MAIL32_MINRAM 70*1024
#endif
#define xPSTR(a) a
#define MAX_ATTCHMENTS 8
char *attachments[MAX_ATTCHMENTS];
@ -20,8 +45,6 @@ SMTPSession *smtp;
//SMTPSession smtp;
void smtpCallback(SMTP_Status status);
//#define DEBUG_EMAIL_PORT
uint16_t SendMail(char *buffer) {
char *params,*oparams = 0;
const char *mserv;
@ -379,8 +402,6 @@ void Tasmota_print(const char *txt) {
#endif
}
#endif // USE_ESP32MAIL
#endif // USE_SENDMAIL
#endif // USE_WEBSERVER
#endif // ESP32

View File

@ -3484,7 +3484,7 @@ const char kWebCommands[] PROGMEM = "|" // No prefix
#ifdef USE_EMULATION
D_CMND_EMULATION "|"
#endif
#if defined(USE_SENDMAIL) || defined(USE_ESP32MAIL)
#ifdef USE_SENDMAIL
D_CMND_SENDMAIL "|"
#endif
D_CMND_WEBSERVER "|" D_CMND_WEBPASSWORD "|" D_CMND_WEBREFRESH "|" D_CMND_WEBSEND "|" D_CMND_WEBQUERY "|"
@ -3505,7 +3505,7 @@ void (* const WebCommand[])(void) PROGMEM = {
#ifdef USE_EMULATION
&CmndEmulation,
#endif
#if defined(USE_SENDMAIL) || defined(USE_ESP32MAIL)
#ifdef USE_SENDMAIL
&CmndSendmail,
#endif
&CmndWebServer, &CmndWebPassword, &CmndWebRefresh, &CmndWebSend, &CmndWebQuery,
@ -3564,9 +3564,8 @@ void CmndEmulation(void)
}
#endif // USE_EMULATION
#if defined(USE_SENDMAIL) || defined(USE_ESP32MAIL)
void CmndSendmail(void)
{
#ifdef USE_SENDMAIL
void CmndSendmail(void) {
if (XdrvMailbox.data_len > 0) {
uint8_t result = SendMail(XdrvMailbox.data);
char stemp1[20];
@ -3575,7 +3574,6 @@ void CmndSendmail(void)
}
#endif // USE_SENDMAIL
void CmndWebServer(void)
{
if ((XdrvMailbox.payload >= 0) && (XdrvMailbox.payload <= 2)) {

View File

@ -6139,7 +6139,7 @@ int16_t Run_script_sub(const char *type, int8_t tlen, struct GVARS *gv) {
}
#if defined(USE_SENDMAIL) || defined(USE_ESP32MAIL)
#ifdef USE_SENDMAIL
else if (!strncmp(lp, "mail", 4)) {
lp+=5;
//char tmp[256];
@ -6151,7 +6151,7 @@ int16_t Run_script_sub(const char *type, int8_t tlen, struct GVARS *gv) {
}
goto next_line;
}
#endif
#endif // USE_SENDMAIL
else if (!strncmp(lp,"=>",2) || !strncmp(lp,"->",2) || !strncmp(lp,"+>",2) || !strncmp(lp,"print",5)) {
// execute cmd
uint8_t sflag = 0,pflg = 0,svmqtt,swll;
@ -9720,7 +9720,7 @@ exgc:
#endif //USE_SCRIPT_WEB_DISPLAY
#if defined(USE_SENDMAIL) || defined(USE_ESP32MAIL)
#ifdef USE_SENDMAIL
void script_send_email_body(void(*func)(char *)) {
uint8_t msect = Run_Scripter1(">m", -2, 0);
@ -9753,7 +9753,7 @@ uint8_t msect = Run_Scripter1(">m", -2, 0);
func((char*)"*");
}
}
#endif //USE_SENDMAIL
#endif // USE_SENDMAIL
#ifdef USE_SCRIPT_JSON_EXPORT
void ScriptJsonAppend(void) {