0% found this document useful (0 votes)
508 views11 pages

Experiment # 1: Using ESP32 To Send Emails Via An SMTP Server

This document provides instructions for using an ESP32 microcontroller to send emails via SMTP. It explains what an SMTP server is and provides common SMTP server settings for Gmail, Outlook, and Hotmail. The ESP-Mail-Client library allows the ESP32 to send emails with or without attachments. The document walks through installing the library, setting up a test email sender account, and includes example code to send an email with HTML or plain text from the ESP32 on boot. The code is well commented to explain how it works and the necessary modifications for user credentials and settings.

Uploaded by

Wasiq Bhatti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
508 views11 pages

Experiment # 1: Using ESP32 To Send Emails Via An SMTP Server

This document provides instructions for using an ESP32 microcontroller to send emails via SMTP. It explains what an SMTP server is and provides common SMTP server settings for Gmail, Outlook, and Hotmail. The ESP-Mail-Client library allows the ESP32 to send emails with or without attachments. The document walks through installing the library, setting up a test email sender account, and includes example code to send an email with HTML or plain text from the ESP32 on boot. The code is well commented to explain how it works and the necessary modifications for user credentials and settings.

Uploaded by

Wasiq Bhatti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Embedded Systems Laboratory 1

Experiment 1

Experiment # 1:
Using ESP32 to send Emails via an
SMTP Server
What is an SMTP server?

An SMTP (Simple Mail Transfer Protocol) server is an application that’s primary


purpose is to send, receive, and/or relay outgoing mail between email senders
and receivers.

An SMTP server will have an address (or addresses) that can be set by the mail
client or application that you are using, and is generally formatted as
smtp.serveraddress.com. (For example, Gmail’s SMTP server address is
smtp.gmail.com, and Twilio SendGrid’s is smtp.sendgrid.com. You can generally
find your SMTP server address in the account or settings section of your mail
client.)

When you send an email, the SMTP server processes your email, decides which
server to send the message to, and relays the message to that server. The
recipient’s inbox service provider, such as Gmail or AOL then downloads the
message and places it in the recipient’s inbox.

ESP Mail Client Library

To send emails with the ESP32, we’ll use the ESP-Mail-Client library. This library
allows the ESP32 to send and receive emails with or without attachments via
SMTP and IMAP servers.

In this experiment, we’ll use SMTP to send an email with and without
attachments. As an example, we’ll send an image (.png) and a text (.txt) file. The
files sent via email can be saved in the ESP32 Filesystem (SPIFFS) or a microSD
card (not covered in this tutorial).
Embedded Systems Laboratory 2
Experiment 1

Installing the ESP-Mail-Client Library

Before proceeding with this tutorial, you need to install the ESP-Mail-Client library.
This library is not available to install through the Arduino IDE Library Manager.
Follow the next steps to install the library:
1. Download ESP-Mail-Client library .zip folder.
2. In your Arduino IDE, go to Sketch > Include Library > Add .ZIP Library.
3. Select the .zip file you’ve just downloaded.
Then, if you go to File > Examples > ESP-Mail-Client, you’ll find several examples that
you can try.

Sender Email (New Account)

We recommend creating a new email account to send the emails to your main
personal email address. Do not use your main personal email to send emails via
ESP32. If something goes wrong in your code or if by mistake you make too many
requests, you can be banned or have your account temporarily disabled.

We’ll use a newly created Gmail.com account to send the emails, but you can use
any other email provider. The receiver email can be your personal email without any
problem.

Gmail SMTP Server Settings

If you’re using a Gmail account, these are the SMTP Server details:

 SMTP Server: smtp.gmail.com


 SMTP username: Complete Gmail address
 SMTP password: Your Gmail password
 SMTP port (TLS): 587
 SMTP port (SSL): 465
 SMTP TLS/SSL required: yes

Outlook SMTP Server Settings


Embedded Systems Laboratory 3
Experiment 1

For Outlook accounts, these are the SMTP Server settings:

 SMTP Server: smtp.office365.com


 SMTP Username: Complete Outlook email address
 SMTP Password: Your Outlook password
 SMTP Port: 587
 SMTP TLS/SSL Required: Yes

Live or Hotmail SMTP Server Settings

For Live or Hotmail accounts, these are the SMTP Server settings:

 SMTP Server: smtp.live.com


 SMTP Username: Complete Live/Hotmail email address
 SMTP Password: Your Windows Live Hotmail password
 SMTP Port: 587
 SMTP TLS/SSL Required: Yes
If you’re using another email provider, you need to search for its SMTP Server
settings. Now, you have everything ready to start sending emails with your ESP32.

Send an Email with HTML or Raw Text with ESP32 (Arduino


IDE)

The following code sends an email via SMTP Server with HTML or raw text. For
demonstration purposes, the ESP32 sends an email once when it boots. Then, you
should be able to modify the code and integrate it into your own projects.

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

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

Code:

#include <Arduino.h>
Embedded Systems Laboratory 4
Experiment 1

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

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"


#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

#define SMTP_HOST "smtp.gmail.com"


#define SMTP_PORT 465

/* The sign in credentials */


#define AUTHOR_EMAIL "YOUR_EMAIL@XXXX.com"
#define AUTHOR_PASSWORD "YOUR_EMAIL_PASS"

/* Recipient's email*/
#define RECIPIENT_EMAIL "RECIPIENTE_EMAIL@XXXX.com"

/* 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());
Embedded Systems Laboratory 5
Experiment 1

Serial.println();

/** Enable the debug via Serial port


* none debug or 0
* basic debug or 1
*/
smtp.debug(1);

/* Set the callback function to get the sending results */


smtp.callback(smtpCallback);

/* Declare the session config data */


ESP_Mail_Session session;

/* Set the session config */


session.server.host_name = SMTP_HOST;
session.server.port = SMTP_PORT;
session.login.email = AUTHOR_EMAIL;
session.login.password = AUTHOR_PASSWORD;
session.login.user_domain = "";

/* Declare the message class */


SMTP_Message message;

/* Set the message headers */


message.sender.name = "ESP";
message.sender.email = AUTHOR_EMAIL;
message.subject = "ESP Test Email";
message.addRecipient("Sara", RECIPIENT_EMAIL);

/*Send HTML message*/


String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent
from ESP board</p></div>";
message.html.content = htmlMsg.c_str();
message.html.content = htmlMsg.c_str();
message.text.charSet = "us-ascii";
message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

/*
Embedded Systems Laboratory 6
Experiment 1

//Send raw text message


String textMsg = "Hello World! - Sent from ESP board";
message.text.content = textMsg.c_str();
message.text.charSet = "us-ascii";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
message.response.notify = esp_mail_smtp_notify_success |
esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;*/

/* Set the custom message header */


//message.addHeader("Message-ID: <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("----------------");
ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());
ESP_MAIL_PRINTF("Message sent failled: %d\n", status.failedCount());
Serial.println("----------------\n");
struct tm dt;
Embedded Systems Laboratory 7
Experiment 1

for (size_t i = 0; i < smtp.sendingResult.size(); i++){


/* Get the result item */
SMTP_Result result = smtp.sendingResult.getItem(i);
time_t ts = (time_t)result.timestamp;
localtime_r(&ts, &dt);

ESP_MAIL_PRINTF("Message No: %d\n", i + 1);


ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");
ESP_MAIL_PRINTF("Date/Time: %d/%d/%d %d:%d:%d\n", dt.tm_year + 1900,
dt.tm_mon + 1, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec);
ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients);
ESP_MAIL_PRINTF("Subject: %s\n", result.subject);
}
Serial.println("----------------\n");
}
}

How the Code Works

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

First, insert your network credentials in the following lines:

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"


#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

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

#define SMTP_HOST "smtp.gmail.com"


#define SMTP_PORT 465

Insert the sender email sign in credentials (complete email and password)
Embedded Systems Laboratory 8
Experiment 1

#define AUTHOR_EMAIL "YOUR_EMAIL@XXXX.com"


#define AUTHOR_PASSWORD "YOUR_EMAIL_PASS"

Insert the recipient email:

#define RECIPIENT_EMAIL "RECIPIENTE_EMAIL@XXXX.com"

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

/* Set the message headers */


message.sender.name = "ESP";
message.sender.email = AUTHOR_EMAIL;
message.subject = "ESP Test Email";
message.addRecipient("Sara", RECIPIENT_EMAIL);

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

//Send raw text message


String textMsg = "Hello World - Sent from ESP board";
message.text.content = textMsg.c_str();
message.text.charSet = "us-ascii";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

If you want to send HTML text instead, uncomment the following lines— you should
insert your HTML text in the htmlMsg variable.

/*Send HTML message*/


/*String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent
from ESP board</p></div>";
message.html.content = htmlMsg.c_str();
message.html.content = htmlMsg.c_str();
message.text.charSet = "us-ascii";
message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;*/

Finally, the following lines send the message:


Embedded Systems Laboratory 9
Experiment 1

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

Demonstration

Upload the code to your ESP32. After uploading, open the Serial Monitor at a baud
rate of 115200. Press the ESP32 Reset button.

If everything went as expected you should get a similar message in the Serial
Monitor.
Embedded Systems Laboratory 10
Experiment 1

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

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

If you’ve enable the raw text message, this is the email that you should receive.
Embedded Systems Laboratory 11
Experiment 1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy