Guides · 10 min read

ESP32 Send Email: Gmail App Password, SMTP and Sensor Alerts

ESP32 send email guide: Gmail app password with ESP Mail Client, SMTP 465/587, sensor threshold alerts, CSV attachments, rate limiting and error codes.

To send email with an ESP32 means your Wi-Fi-connected board writes straight to your inbox when a sensor crosses a threshold, a door opens or a daily report is due. The ESP32 does this over the SMTP protocol by connecting and logging in to an email server such as Gmail; no paid service or computer is needed in between. In the Arduino IDE the most common way is Mobizt's ESP Mail Client library together with a Gmail app password.

In this guide you'll see how SMTP works, the difference between ports 465 and 587, how to get a Gmail app password step by step and why you shouldn't hard-code that password. Then you'll send your first email, set up a temperature alert email with a DHT22, limit how often emails go out and send your readings as a CSV attachment. You'll also learn how to do the same with ReadyMail, which the library's author recommended as its replacement in 2025, and what the most common error messages mean.

ESP32 development board
Thanks to its built-in Wi-Fi, the ESP32 can connect to an SMTP server and send email without extra hardware.

How does an ESP32 send email? The logic of SMTP

The protocol used to send email is called SMTP (Simple Mail Transfer Protocol). The ESP32 first connects to Wi-Fi, then opens an encrypted TLS connection to your email provider's SMTP server (smtp.gmail.com for Gmail). It introduces itself, logs in with an email address and password, sends the recipient, subject and text, and the server delivers the message to the recipient's inbox. In other words, the ESP32 behaves like an email client, just like the mail app on your phone. The hardest part is the TLS encryption: the ESP32 uses about 40–50 KB of RAM for it, and one send takes 2–5 seconds depending on the network. That's why the ESP8266 struggles and small boards like the Arduino Uno can't do it at all, while the ESP32 handles it comfortably. You can also see the Wi-Fi basics in the ESP32 WiFiManager article.

PortSecurityHow it worksUse on the ESP32
465SSL/TLS (implicit)The connection is encrypted from the very startRecommended for Gmail; the fewest problems
587STARTTLSConnects in plain text, then switches to encryption with STARTTLSSupported by ESP Mail Client; some libraries need a separate client
25UnencryptedFor server-to-server trafficBlocked by most internet providers; not suitable for Gmail users

How do you get a Gmail app password?

  1. Create a separate Gmail account for the ESP32; don't give your personal account to a device. If something goes wrong, only this account is affected.
  2. In your Google Account settings, open Security and turn on 2-Step Verification. App passwords can only be created on accounts with 2-Step Verification turned on.
  3. Type "App passwords" into the search box at the top of the account settings and open the page.
  4. Give the app a recognizable name such as "ESP32 alarm" and press Create.
  5. Copy the 16-character password shown on screen; the spaces are only for readability, so type it into the code without spaces. It won't be shown again.
  6. Put this app password in the AUTHOR_PASSWORD field in the code instead of your normal Gmail password.
SMTP login with your normal Gmail password doesn't work; Google removed the old "less secure apps" option, and devices that log in with the password get "534 Application-specific password required" or "535 Username and Password not accepted". The app password option may not appear on accounts with Advanced Protection, when 2-Step Verification is set up only with security keys, or on school and work accounts (unless the admin allows it). When you change your Google Account password, all app passwords are revoked; you'll need to create a new one and put it in your code.

Don't hard-code the password: storing it safely

An app password gives almost full access to the Gmail account: anyone who knows it can send email from that account and read its inbox over IMAP. That's why writing the password straight into the .ino file and posting the code on GitHub, a forum or a class group is the most common security mistake. The simplest safeguard is to put the credentials in a separate tab in the Arduino IDE, for example an arduino_secrets.h file, and pull it into the main code with #include "arduino_secrets.h"; when you share the code you don't share that file, and if you use Git you add it to .gitignore. To go one step further, take the password once during setup over the serial port or a configuration page and save it to the ESP32's NVS memory with the Preferences library; then it never appears in the code. Remember that if encryption isn't enabled, the ESP32's flash can be read out with esptool; if you lose the device, revoke the app password in your Google Account right away. In the example code the credentials sit at the top as #define lines for readability; move them to a separate file in your real project.

MethodHow safe?When to use it
#define inside the codeWeakest; the password leaves with the code when you share itOnly a quick test on your own desk
Separate arduino_secrets.h tabPrevents accidental leaks when sharingThe minimum recommended for every project
Write once to NVS with PreferencesNot visible in the code; can be extracted if the flash is readDevices you give away or sell
Separate Gmail account + app passwordIf leaked, only that account is affected and the password is revoked with one clickAlways, together with the others
Flash encryption (ESP32 security feature)Flash contents can't be readAdvanced, for devices that become products

Library: installing ESP Mail Client

Open the Library Manager in the Arduino IDE, search for "ESP Mail Client" and install Mobizt's library (the code in this article was compiled with version 3.4.24). The library supports sending over SMTP, reading over IMAP, HTML bodies, attachments and inline images; besides the ESP32 and ESP8266 it also runs on boards such as the Pico W. There's one important detail: in 2025 the author marked this library as "deprecated" and recommended his ReadyMail library for new projects. ESP Mail Client can still be installed, it works and most examples on the internet use it, but it won't get new updates. At the end of the article there's a short example that sends the same email with ReadyMail.

Your first email: the code step by step

C++ (Arduino IDE)
1// ESP32 ile Gmail üzerinden ilk e-posta (ESP Mail Client 3.x)
2// First email from an ESP32 through Gmail (ESP Mail Client 3.x)
3#include <WiFi.h>
4#include <ESP_Mail_Client.h>
5
6// Bu bilgileri paylaştığın koda yazma / never put these in code you share
7#define WIFI_SSID       "WIFI_ADIN"
8#define WIFI_PASSWORD   "WIFI_SIFREN"
9#define SMTP_HOST       "smtp.gmail.com"
10#define SMTP_PORT       465                      // 465 = SSL, 587 = STARTTLS
11#define AUTHOR_EMAIL    "[email protected]"     // gönderen hesap / sender account
12#define AUTHOR_PASSWORD "abcdabcdabcdabcd"       // 16 haneli uygulama şifresi / 16-character app password
13#define RECIPIENT_EMAIL "[email protected]"        // alıcı / recipient
14
15SMTPSession smtp;
16
17void smtpCallback(SMTP_Status status) {        // gönderim durumu / sending status
18  Serial.println(status.info());
19  if (status.success()) {
20    Serial.printf("Gonderildi / Sent: %d, Hata / Failed: %d\n",
21                  status.completedCount(), status.failedCount());
22    smtp.sendingResult.clear();                // belleği boşalt / free the memory
23  }
24}
25
26void setup() {
27  Serial.begin(115200);
28  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
29  Serial.print("Wi-Fi");
30  while (WiFi.status() != WL_CONNECTED) {
31    Serial.print('.');
32    delay(300);
33  }
34  Serial.println(WiFi.localIP());
35
36  MailClient.networkReconnect(true);           // bağlantı koparsa yeniden bağlan / reconnect if dropped
37  smtp.debug(1);                               // 0 = sessiz, 1 = temel günlük / 0 = silent, 1 = basic log
38  smtp.callback(smtpCallback);
39
40  Session_Config config;
41  config.server.host_name = SMTP_HOST;
42  config.server.port = SMTP_PORT;
43  config.login.email = AUTHOR_EMAIL;
44  config.login.password = AUTHOR_PASSWORD;
45  config.login.user_domain = F("127.0.0.1");
46  config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
47  config.time.gmt_offset = 3;                  // Türkiye UTC+3 / Turkey UTC+3
48  config.time.day_light_offset = 0;
49
50  SMTP_Message message;
51  message.sender.name = F("ESP32");
52  message.sender.email = AUTHOR_EMAIL;
53  message.subject = F("ESP32'den merhaba / Hello from ESP32");
54  message.addRecipient(F("Alici"), RECIPIENT_EMAIL);
55  message.text.content = "Bu e-posta bir ESP32 tarafindan gonderildi.\r\nThis email was sent by an ESP32.";
56  message.text.charSet = F("utf-8");
57  message.text.transfer_encoding = Content_Transfer_Encoding::enc_base64;
58
59  if (!smtp.connect(&config)) {                // sunucuya bağlan ve giriş yap / connect and log in
60    Serial.printf("Baglanti hatasi / Connection error %d: %s\n",
61                  smtp.errorCode(), smtp.errorReason().c_str());
62    return;
63  }
64  if (!MailClient.sendMail(&smtp, &message)) { // gönder ve oturumu kapat / send and close the session
65    Serial.printf("Gonderim hatasi / Send error %d: %s\n",
66                  smtp.errorCode(), smtp.errorReason().c_str());
67  }
68}
69
70void loop() {}

The code connects to Wi-Fi, fills the Session_Config structure with the server, port and login details, and prepares the sender, recipient, subject and text with SMTP_Message. smtp.connect() connects and logs in to the server, and MailClient.sendMail() sends the email and closes the session. The user_domain field is used when introducing yourself to the server; if you don't have a domain, 127.0.0.1 is enough, while random text can make some servers reject the connection. The NTP setting fetches the time from the internet for the email's Date header; if the time can't be set, the library returns error -404 or -406. For text with accented characters, setting charSet to utf-8 and transfer_encoding to base64 prevents garbled letters. smtp.debug(1) prints every step of the connection to the Serial Monitor; keep it on for the first attempt and set it to 0 once everything works.

Alert email at a sensor threshold

In a real project an email should go out when something happens. The example below measures the temperature with a DHT22 every 5 seconds and sends an alert email when it goes above 30 °C. Connect the DHT22's VCC to 3V3, GND to GND and the data pin to GPIO 4; if you're using a bare sensor, put a 10 kΩ resistor between data and 3V3 (modules already have it). The code uses three layers of protection: hysteresis (the alarm isn't re-armed until the temperature drops below 28 °C), a minimum gap (at least 15 minutes between two emails) and a daily limit (at most 10 emails a day). To get to know the DHT22 better, see the ESP32 DHT22 web server article.

C++ (Arduino IDE)
1// ESP32 sıcaklık alarmı: eşik, histerezis ve e-posta sıklığı sınırı (DHT22)
2// ESP32 temperature alarm: threshold, hysteresis and email rate limit (DHT22)
3#include <WiFi.h>
4#include <ESP_Mail_Client.h>
5#include <DHT.h>
6
7#define WIFI_SSID       "WIFI_ADIN"
8#define WIFI_PASSWORD   "WIFI_SIFREN"
9#define AUTHOR_EMAIL    "[email protected]"
10#define AUTHOR_PASSWORD "abcdabcdabcdabcd"       // uygulama şifresi / app password
11#define RECIPIENT_EMAIL "[email protected]"
12
13const int DHT_PIN = 4;                           // DHT22 veri pini / DHT22 data pin
14const float ALARM_ON = 30.0;                     // bu değerin üstünde alarm / alarm above this
15const float ALARM_OFF = 28.0;                    // bunun altına inince yeniden kurulur / re-armed below this
16const unsigned long MIN_GAP = 15UL * 60 * 1000;  // iki e-posta arası en az 15 dk / at least 15 min between emails
17const int MAX_PER_DAY = 10;                      // günde en fazla 10 e-posta / at most 10 emails a day
18const unsigned long DAY = 24UL * 60 * 60 * 1000;
19
20DHT dht(DHT_PIN, DHT22);
21SMTPSession smtp;
22Session_Config config;
23
24bool armed = true;                 // alarm kurulu mu / is the alarm armed
25bool firstMail = true;
26unsigned long lastMail = 0, dayStart = 0;
27int sentToday = 0;
28
29bool sendAlert(float t, float h) {
30  SMTP_Message message;
31  message.sender.name = F("ESP32 Alarm");
32  message.sender.email = AUTHOR_EMAIL;
33  message.subject = "Sicaklik alarmi / Temperature alarm: " + String(t, 1) + " C";
34  message.addRecipient(F("Alici"), RECIPIENT_EMAIL);
35  message.text.content = "Sicaklik / Temperature: " + String(t, 1) + " C\r\nNem / Humidity: %" +
36                         String(h, 0) + "\r\nEsik / Threshold: " + String(ALARM_ON, 1) + " C";
37  message.text.charSet = F("utf-8");
38  message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_high;
39
40  if (!smtp.connect(&config)) {
41    Serial.printf("Baglanti hatasi / Connection error %d: %s\n", smtp.errorCode(), smtp.errorReason().c_str());
42    return false;
43  }
44  if (!MailClient.sendMail(&smtp, &message)) {
45    Serial.printf("Gonderim hatasi / Send error %d: %s\n", smtp.errorCode(), smtp.errorReason().c_str());
46    return false;
47  }
48  smtp.sendingResult.clear();
49  return true;
50}
51
52void setup() {
53  Serial.begin(115200);
54  dht.begin();
55  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
56  while (WiFi.status() != WL_CONNECTED) delay(300);
57  MailClient.networkReconnect(true);
58
59  config.server.host_name = "smtp.gmail.com";
60  config.server.port = 465;
61  config.login.email = AUTHOR_EMAIL;
62  config.login.password = AUTHOR_PASSWORD;
63  config.login.user_domain = F("127.0.0.1");
64  config.time.ntp_server = F("pool.ntp.org");
65  config.time.gmt_offset = 3;
66}
67
68void loop() {
69  static unsigned long lastRead = 0;
70  if (millis() - lastRead < 5000) return;        // 5 sn'de bir ölç / measure every 5 s
71  lastRead = millis();
72
73  float t = dht.readTemperature();
74  float h = dht.readHumidity();
75  if (isnan(t) || isnan(h)) return;              // okuma hatası / read error
76  Serial.printf("T=%.1f C  H=%.0f %%\n", t, h);
77
78  if (millis() - dayStart > DAY) { dayStart = millis(); sentToday = 0; }  // günlük sayaç / daily counter
79  if (!armed && t < ALARM_OFF) armed = true;     // sıcaklık düştü, yeniden kur / cooled down, re-arm
80
81  bool gapOk = firstMail || millis() - lastMail > MIN_GAP;
82  if (armed && t > ALARM_ON && gapOk && sentToday < MAX_PER_DAY) {
83    if (sendAlert(t, h)) {
84      armed = false;                             // düşene kadar tekrar gönderme / don't resend until it drops
85      firstMail = false;
86      lastMail = millis();
87      sentToday++;
88    }
89  }
90}

Without hysteresis, a new email would go out on every reading as the temperature wobbles between 29.9 and 30.1 °C. The armed variable becomes false once the alarm fires and only turns true again when the temperature falls below ALARM_OFF. MIN_GAP puts 15 minutes between two emails even if the temperature swings quickly, and MAX_PER_DAY keeps your inbox from filling up if something breaks. If sending fails (Wi-Fi dropped, the server didn't answer), armed stays true and it tries again on the next reading. sendMail() blocks for a few seconds and loop() stops during that time, so move tasks that need a quick reaction (motors, buttons) to a separate FreeRTOS task or run them before sending.

Why does limiting how often you send matter?

RiskWhat happens?Safeguard
Gmail sending quotaAbout 500 recipients a day on personal accounts; beyond that the account can't send for up to 24 hoursSet a daily limit with MAX_PER_DAY
Spam detectionMany emails with the same subject land in spam or the account is temporarily lockedOne email per event, use summary reports
Sensor noiseEvery reading at the threshold creates a new alarmHysteresis and averaging several readings
Faulty sensorConstant alarms with NaN or nonsense valuesisnan() check and a plausible range check
Battery lifeEvery TLS connection means 2–5 seconds of high currentWake from deep sleep, measure, send if needed, sleep

Sending attachments: a CSV report

ESP Mail Client can take an attachment in two ways: from data in RAM (a blob) or from a file on LittleFS or an SD card. The example below reads an analog sensor (GPIO 34, ADC1) once an hour, collects the values in RAM as CSV text and every 24 readings sends an email with a rapor.csv attachment. A semicolon-separated CSV splits straight into columns in Excel with German or Turkish regional settings; with English settings use the import wizard or change the separator to a comma. This example also uses port 587 (STARTTLS); ESP Mail Client supports both ports with the same settings. For large files use the file system instead of RAM: set att.file.path to a path such as "/log.csv" and att.file.storage_type to esp_mail_file_storage_type_flash or esp_mail_file_storage_type_sd. Gmail limits the total size of an email to 25 MB, but for the ESP32 the practical limit is connection time; attachments over a few hundred KB take a long time.

C++ (Arduino IDE)
1// ESP32 günlük rapor: ölçümleri CSV ek dosyası olarak e-postayla gönder
2// ESP32 daily report: email the measurements as a CSV attachment
3#include <WiFi.h>
4#include <ESP_Mail_Client.h>
5
6#define WIFI_SSID       "WIFI_ADIN"
7#define WIFI_PASSWORD   "WIFI_SIFREN"
8#define AUTHOR_EMAIL    "[email protected]"
9#define AUTHOR_PASSWORD "abcdabcdabcdabcd"       // uygulama şifresi / app password
10#define RECIPIENT_EMAIL "[email protected]"
11
12const int SENSOR = 34;                           // analog sensör (ADC1) / analog sensor (ADC1)
13const int SAMPLES = 24;                          // rapordaki satır sayısı / rows in the report
14const unsigned long PERIOD = 60UL * 60 * 1000;   // saatte bir ölçüm / one sample per hour
15
16SMTPSession smtp;
17Session_Config config;
18String csv;                                      // CSV metni RAM'de / CSV text in RAM
19int rows = 0;
20
21bool sendReport() {
22  SMTP_Message message;
23  message.sender.name = F("ESP32 Rapor");
24  message.sender.email = AUTHOR_EMAIL;
25  message.subject = F("Gunluk rapor / Daily report");
26  message.addRecipient(F("Alici"), RECIPIENT_EMAIL);
27  message.text.content = "Ekte son " + String(rows) + " olcum var.\r\nAttached are the last " + String(rows) + " readings.";
28
29  SMTP_Attachment att;                           // bellekten ek dosya / attachment from memory
30  att.descr.filename = F("rapor.csv");
31  att.descr.mime = F("text/csv");
32  att.blob.data = (const uint8_t *)csv.c_str();
33  att.blob.size = csv.length();
34  att.descr.transfer_encoding = Content_Transfer_Encoding::enc_base64;
35  message.addAttachment(att);
36
37  if (!smtp.connect(&config)) return false;
38  bool ok = MailClient.sendMail(&smtp, &message);
39  if (!ok) Serial.printf("Hata / Error %d: %s\n", smtp.errorCode(), smtp.errorReason().c_str());
40  smtp.sendingResult.clear();
41  return ok;
42}
43
44void setup() {
45  Serial.begin(115200);
46  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
47  while (WiFi.status() != WL_CONNECTED) delay(300);
48  MailClient.networkReconnect(true);
49
50  config.server.host_name = "smtp.gmail.com";
51  config.server.port = 587;                      // STARTTLS örneği / STARTTLS example
52  config.login.email = AUTHOR_EMAIL;
53  config.login.password = AUTHOR_PASSWORD;
54  config.login.user_domain = F("127.0.0.1");
55  config.time.ntp_server = F("pool.ntp.org");
56  config.time.gmt_offset = 3;
57
58  csv = "saat;deger\r\n";                        // başlık satırı / header row
59}
60
61void loop() {
62  static unsigned long last = 0;
63  if (rows > 0 && millis() - last < PERIOD) return;
64  last = millis();
65
66  int value = analogRead(SENSOR);
67  csv += String(rows) + ";" + String(value) + "\r\n";
68  rows++;
69
70  if (rows >= SAMPLES) {
71    if (sendReport()) {                          // gönderildiyse sıfırla / reset after sending
72      csv = "saat;deger\r\n";
73      rows = 0;
74    }
75  }
76}

Sending the same email with ReadyMail

ReadyMail is a lighter, asynchronous new library written from scratch by the author of ESP Mail Client; you'll find it in the Library Manager as "ReadyMail" (compiled here with version 0.4.2). For SMTP you write #define ENABLE_SMTP at the top of the code, the connection is made with WiFiClientSecure and the email headers are added with rfc822_from, rfc822_to and rfc822_subject. It hasn't reached version 1.0 yet, so its API may change. Its license is also different: ESP Mail Client is MIT licensed, while ReadyMail comes under CC BY-NC 4.0 and requires a separate license for commercial products; read the license terms before using it in a device you'll sell. setInsecure() in the example doesn't verify the server certificate; it's handy for testing, but on a permanent device it's safer to provide the root certificate with setCACert().

C++ (Arduino IDE)
1// ReadyMail ile e-posta (ESP Mail Client'ın yeni kardeşi)
2// Email with ReadyMail (the successor of ESP Mail Client)
3#include <WiFi.h>
4#include <WiFiClientSecure.h>
5#define ENABLE_SMTP
6#include <ReadyMail.h>
7
8#define WIFI_SSID       "WIFI_ADIN"
9#define WIFI_PASSWORD   "WIFI_SIFREN"
10#define AUTHOR_EMAIL    "[email protected]"
11#define AUTHOR_PASSWORD "abcdabcdabcdabcd"       // uygulama şifresi / app password
12#define RECIPIENT_EMAIL "[email protected]"
13
14WiFiClientSecure sslClient;
15SMTPClient smtp(sslClient);
16
17void setup() {
18  Serial.begin(115200);
19  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
20  while (WiFi.status() != WL_CONNECTED) delay(300);
21
22  configTime(3 * 3600, 0, "pool.ntp.org");       // Date başlığı için saat / clock for the Date header
23  while (time(nullptr) < 100000) delay(100);
24
25  sslClient.setInsecure();                       // sertifika doğrulaması yok (test için) / no certificate check (testing)
26  auto statusCallback = [](SMTPStatus status) { Serial.println(status.text); };
27
28  smtp.connect("smtp.gmail.com", 465, statusCallback);
29  if (!smtp.isConnected()) return;
30  smtp.authenticate(AUTHOR_EMAIL, AUTHOR_PASSWORD, readymail_auth_password);
31
32  SMTPMessage msg;
33  msg.headers.add(rfc822_from, "ESP32 <" AUTHOR_EMAIL ">");
34  msg.headers.add(rfc822_to, "Alici <" RECIPIENT_EMAIL ">");
35  msg.headers.add(rfc822_subject, "ReadyMail ile merhaba / Hello with ReadyMail");
36  msg.text.body("Bu e-posta ReadyMail ile gonderildi.\r\nThis email was sent with ReadyMail.");
37  msg.timestamp = time(nullptr);
38  smtp.send(msg);
39}
40
41void loop() {}

Error messages and fixes

Error (code or server message)MeaningFix
534 5.7.9 Application-specific password requiredLogin was attempted with the normal Gmail passwordCreate an app password and use it
535 5.7.8 Username and Password not acceptedEmail or app password wrong, revoked or typed with spacesType the password without spaces; if your Google password changed, create a new one
-100 SMTP_STATUS_SERVER_CONNECT_FAILEDCould not connect to the serverCheck Wi-Fi, server name and port; the network may block 465/587
-104 / -105 / -106 authentication errorsThe login step failedCheck AUTHOR_EMAIL and AUTHOR_PASSWORD, make sure 2-Step Verification is on
-108 SMTP_STATUS_SEND_HEADER_RECIPIENT_FAILEDThe recipient address was rejectedCheck the spelling of the recipient address
-401 MAIL_CLIENT_ERROR_READ_TIMEOUTThe server didn't answer in timeImprove the signal and retry; common on weak Wi-Fi
-403 MAIL_CLIENT_ERROR_OUT_OF_MEMORYNot enough RAM for TLSShrink large Strings and arrays, send attachments from a file
-404 MAIL_CLIENT_ERROR_NTP_TIME_SYNC_TIMED_OUTCouldn't get the time from the internetChange the NTP server (pool.ntp.org), check that Wi-Fi reaches the internet
550 5.4.5 Daily user sending limit exceededThe daily sending quota is used upWait 24 hours, send less often
When you get an error, first look at the log in the Serial Monitor with smtp.debug(1); the three-digit reply code from the server (such as 534, 535 or 550) tells you directly where the problem is. You can print the library's own negative error code with smtp.errorCode() and its description with smtp.errorReason().

ESP32 email project ideas

  • Idea: Build an alarm with a PIR motion sensor that sends an alert email when motion is detected while nobody is home.
  • Idea: Make a detector with an MQ-2 gas sensor that sounds a buzzer and sends an email when there's a gas leak in the kitchen.
  • Idea: Measure temperature and soil moisture in a greenhouse every hour and email the CSV report every morning at 08:00.
  • Idea: Send an email when a water tank level drops to a critical point and a "problem solved" email when it returns to normal.
  • Idea: Let a battery-powered sensor sleep for hours with deep sleep and wake up to send an email only when the threshold is crossed.
  • Idea: For instant notifications, also send the same event to your phone with an ESP32 Telegram bot; email for the record, Telegram for the quick alert.

Sending email with an ESP32 takes just a few minutes with the right SMTP settings, an app password and a well-thought-out sending limit, and it gives your projects a lasting "let me know" ability. If you'd like to practice connecting to Wi-Fi and getting the time from the internet first, check the wiring diagrams and code of the "ESP32 Wi-Fi STA Connection (with LCD)" and "ESP32 Real Time from the Internet with NTP" projects in the BlueGrays app, and for the sensor side the "ESP32 DHT22 Temperature and Humidity (with LCD)" and "ESP32 MQ-2 Gas/Smoke Detector Alarm" projects, step by step.

Frequently asked questions

Can an ESP32 send email through Gmail?

Yes. With the ESP Mail Client or ReadyMail library, the ESP32 can connect to smtp.gmail.com on port 465 (SSL) or 587 (STARTTLS) and send email. To log in you need the 16-character app password created with 2-Step Verification turned on, not your normal Gmail password.

Why can't I see the Gmail app password option?

App passwords can only be created on accounts with 2-Step Verification turned on. The option may not appear if 2-Step Verification is set up only with security keys, if the account has Advanced Protection, or if it's a school or work account. Creating a separate personal Gmail account for the ESP32 is the easiest fix.

Should I use port 465 or 587 for ESP32 email?

Both work with Gmail. Port 465 opens the connection with SSL from the start and usually causes the fewest problems on the ESP32. Port 587 connects in plain text first and then switches to encryption with STARTTLS; ESP Mail Client supports both with the same settings.

What causes the "535 Username and Password not accepted" error on the ESP32?

It means Gmail rejected the login details: the email address or app password is wrong, or the password was typed with spaces or has been revoked. Changing your Google Account password revokes all app passwords. Create a new app password and type it without spaces.

Can an ESP32 attach files to an email?

Yes. With SMTP_Attachment in ESP Mail Client you can send data from RAM or a file from LittleFS or an SD card as an attachment. Attaching sensor readings as a CSV is the most common use; for large files, sending from the file system instead of RAM avoids memory errors.

How many emails can an ESP32 send per day?

The ESP32 itself has no limit; the email provider sets it. On personal Gmail accounts the daily limit is about 500 recipients, and if you exceed it the account can't send for a while. Using hysteresis, a minimum gap between emails and a daily cap in your project protects both the quota and against spam filters.

See all projects
ESP32 Wi-Fi STA Connection (with LCD Screen)
ES-25Advanced

ESP32 Wi-Fi STA Connection (with LCD Screen)

In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

4.4(21)
41
Real-Time Clock from the Internet via ESP32 NTP
ES-26Advanced
Premium

Real-Time Clock from the Internet via ESP32 NTP

The ESP32 connects to Wi-Fi and fetches the real time from NTP (Network Time Protocol) servers with millisecond precision. configTzTime() applies the Turkey time zone (TRT, UTC+3) automatically, and in countries with daylight saving time the DST switch is handled by a POSIX TZ string. The time is printed both to the Serial Monitor and to an optional I2C LCD.

4.5(13)
22
ESP32 DHT22 Temperature and Humidity (with LCD Display)
ES-15Intermediate

ESP32 DHT22 Temperature and Humidity (with LCD Display)

This project measures ambient temperature and humidity using a DHT22 sensor and displays the data in real time on a 16x2 I2C LCD. Data is read from the sensor using the one-wire protocol via the Adafruit DHT library. This project serves as the foundation for IoT weather stations, smart home automation, or environmental monitoring systems in greenhouses. Communication with the DHT22 is established via the ESP32's GPIO 4 pin.

4.8(38)
57
ESP32 MQ-2 Gas/Smoke Detector Alarm
ES-20Intermediate

ESP32 MQ-2 Gas/Smoke Detector Alarm

In this project, combustible gas (LPG, methane, propane) and smoke detection is performed using an MQ-2 gas sensor module, and a siren-like alarm is played through a passive buzzer upon detection. The sensor's digital threshold output (DO) is connected to GPIO 4 on the ESP32; when gas or smoke exceeds the threshold, DO goes LOW and the alarm is triggered. Sensitivity is adjusted via the module's potentiometer. The passive buzzer is driven using tone() to produce a two-frequency siren effect.

4.7(29)
47
ESP32 Motion Alarm System (PIR + Buzzer + LED + Telegram)
ES-41Advanced
Premium

ESP32 Motion Alarm System (PIR + Buzzer + LED + Telegram)

A smart security alarm: when the PIR sensor detects motion, it sounds the buzzer, lights the LED and sends the owner an instant Telegram notification. A 30-second cooldown limits how often the alarm repeats; it does not filter out the PIR sensor's false detections. Use it at home, in a garage, a storeroom or a study.

4.0(1)
9
ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)
ES-40Advanced
Premium

ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)

Build a timed temperature and humidity logger with the ESP32! A DHT22 sensor reads temperature and humidity once a minute, and each reading is saved to a microSD card in CSV format with a real-time stamp from the DS1307 RTC module. The OLED display shows the latest temperature, humidity, timestamp and total number of records live, in large text.

4.7(7)
12
ESP32 HTTPClient + Weather API (with LCD Screen)
ES-31Advanced
Premium

ESP32 HTTPClient + Weather API (with LCD Screen)

In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. The JSON response is parsed with ArduinoJson v7, and the city, temperature, humidity, weather and wind are shown on an I2C LCD. wttr.in needs no API key; just type the name of any city.

4.7(13)
20