ESP32 Mailbox Notifier: Reed Switch, Deep Sleep and Telegram
Build an ESP32 mailbox notifier: a reed switch wakes it from deep sleep to send a Telegram or e-mail alert. Battery life table, metal box Wi-Fi and ESP-NOW.
An ESP32 mailbox notifier is a small but very handy IoT project that saves you pointless trips to the front door. The idea is simple: you put a magnet on the mailbox lid and a reed switch on the body; when the lid opens, the ESP32 wakes from deep sleep, connects to Wi-Fi, sends a Telegram message or an e-mail to your phone and goes back to sleep within a few seconds. Because it spends 99.9 percent of its time asleep, it can run for months on a single 18650 cell, and for years with the right board.
In this guide we'll build, step by step, how the reed switch wakes the ESP32, a wiring that draws almost no current during sleep, and code that doesn't fall into an endless wake-up loop if the lid stays open. You'll also find the Telegram and e-mail versions, a battery life table with real current figures, fixes for metal mailboxes that weaken the signal and an ESP-NOW gateway setup for distant garden gates where Wi-Fi doesn't reach.

How does an ESP32 mailbox notifier work?
The heart of the system is the ESP32's deep sleep mode. In this mode the CPU cores, Wi-Fi and most of the memory are switched off; only the small RTC domain stays on, and a bare ESP32 module draws about 10–15 µA. With the wake-up source called ext0, the RTC domain can watch the level of one pin: the moment the pin reaches the level you chose, the chip wakes up and runs the program from the start, from setup(). A reed switch is ideal for this because it's a passive switch that uses no power at all. You'll find more about reed switches in the reed switch guide and all the sleep modes in the ESP32 deep sleep guide.
- The lid is closed and the magnet sits next to the reed; the reed is closed, GPIO 33 is HIGH and the ESP32 is in deep sleep.
- The postman opens the lid and the magnet moves away; the reed opens and the 1 MΩ resistor pulls the pin LOW.
- The RTC unit sees the LOW level, the ESP32 wakes in about 0.2 seconds and setup() runs from the start.
- The code sees that the wake-up cause was ext0, increments the counter, connects to Wi-Fi and sends the notification.
- If the lid is still open, the ESP32 sleeps waiting for it to close (HIGH) this time; if it's closed, it sleeps waiting for the next opening (LOW).
- Connecting to Wi-Fi and sending the message takes 3–6 seconds in total; the rest of the day is spent asleep.
Parts and wiring
| Part | Connection | Note |
|---|---|---|
| Reed switch (normally open, NO) | One end to 3V3, the other to GPIO 33 | On the mailbox body, at the edge where the lid closes |
| Magnet | On the lid, 5–10 mm from the reed | A neodymium magnet works from further away |
| 1 MΩ resistor | Between GPIO 33 and GND | Pull-down: holds the pin LOW when the lid is open |
| ESP32 (low sleep current board recommended) | Battery to 3V3 through a regulator | DevKit boards draw mA in sleep, see the table below |
| 18650 Li-ion cell + low quiescent current LDO | Battery + to LDO input; LDO output to 3V3 | Add 470–1000 µF for the Wi-Fi bursts |
| TP4056 charger module (optional) | Across the battery | Charge over USB without removing the cell |
Why did we connect the reed to 3V3 and the resistor to GND? The lid is closed almost all day, so the reed is closed too. While the reed is closed, a small current flows constantly through the resistor: I = V / R = 3.3 V / 1 MΩ = 3.3 µA. The ESP32's internal RTC pull-down is about 45 kΩ, so using it would raise this current to 73 µA and multiply the sleep current five times. That's why the code turns the internal resistors off and uses the external 1 MΩ. If you have a reed that opens when a magnet comes close (normally closed, NC), no current flows with the lid closed; the wiring stays the same and only the levels in the code swap.
Preparing the Telegram bot
- In Telegram open BotFather, type /newbot and give your bot a name and a username ending in bot.
- Copy the token BotFather gives you; it's your bot's password, don't share it with anyone.
- To find your own chat ID, send /getid to an ID bot such as IDBot and note the number you get.
- Find your own bot and send it /start once; this step is required before the bot can message you first.
- In the Arduino IDE, install the UniversalTelegramBot and ArduinoJson libraries from the Library Manager.
- Replace the Wi-Fi name, password, token and chat ID lines in the code with your own. For a detailed bot setup see the ESP32 Telegram bot guide.
Code: a Telegram message when the lid opens
1// ESP32 posta kutusu bildirimi: reed sensör + derin uyku + Telegram
2// ESP32 mailbox notifier: reed switch + deep sleep + Telegram
3#include <WiFi.h>
4#include <WiFiClientSecure.h>
5#include <UniversalTelegramBot.h>
6#include "driver/rtc_io.h"
7
8const char* WIFI_SSID = "AgAdi"; // 2,4 GHz Wi-Fi adı / 2.4 GHz Wi-Fi name
9const char* WIFI_PASS = "Sifre123";
10#define BOT_TOKEN "1234567890:AAExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" // BotFather token
11#define CHAT_ID "123456789" // kendi Telegram ID'n / your Telegram ID
12
13// Reed: GPIO 33 ile 3V3 arası; 1 MΩ: GPIO 33 ile GND arası
14// Reed: between GPIO 33 and 3V3; 1 MΩ: between GPIO 33 and GND
15const gpio_num_t REED_PIN = GPIO_NUM_33; // RTC GPIO olmalı / must be an RTC GPIO
16const unsigned long WIFI_TIMEOUT_MS = 10000;
17
18RTC_DATA_ATTR uint32_t mailCount = 0; // derin uykuda korunur / kept in deep sleep
19RTC_DATA_ATTR bool waitingForClose = false; // kapanmayı mı bekliyoruz? / waiting for the lid to close?
20
21WiFiClientSecure client;
22UniversalTelegramBot bot(BOT_TOKEN, client);
23
24bool lidIsOpen() { // mıknatıs uzakta: LOW / magnet away: LOW
25 return digitalRead(REED_PIN) == LOW;
26}
27
28bool connectWiFi() {
29 WiFi.mode(WIFI_STA);
30 WiFi.begin(WIFI_SSID, WIFI_PASS);
31 unsigned long start = millis();
32 while (WiFi.status() != WL_CONNECTED) {
33 if (millis() - start > WIFI_TIMEOUT_MS) return false; // pili boşa harcama / don't waste the battery
34 delay(100);
35 }
36 return true;
37}
38
39void goToSleep() {
40 bool open = lidIsOpen();
41 waitingForClose = open; // açıksa kapanmayı bekle / if open, wait for closing
42 rtc_gpio_pullup_dis(REED_PIN); // dahili dirençler kapalı, dıştaki 1 MΩ yeter
43 rtc_gpio_pulldown_dis(REED_PIN); // internal pulls off, the external 1 MΩ is enough
44 esp_sleep_enable_ext0_wakeup(REED_PIN, open ? 1 : 0); // 0: LOW ile uyan / 0: wake on LOW
45 Serial.println(open ? "Uyku: kapanma bekleniyor / waiting for close"
46 : "Uyku: acilma bekleniyor / waiting for open");
47 Serial.flush();
48 esp_deep_sleep_start();
49}
50
51void setup() {
52 Serial.begin(115200);
53 rtc_gpio_deinit(REED_PIN); // pini normal GPIO'ya döndür / back to a normal GPIO
54 pinMode(REED_PIN, INPUT);
55 delay(50); // kontak sıçraması için bekle / let the contact settle
56
57 esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
58 if (cause == ESP_SLEEP_WAKEUP_EXT0 && !waitingForClose) { // kapak açıldı / lid opened
59 mailCount++;
60 if (connectWiFi()) {
61 client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // api.telegram.org kök sertifikası / root CA
62 String text = "Posta kutusu acildi / Mailbox opened (#" + String(mailCount) +
63 ", RSSI " + String(WiFi.RSSI()) + " dBm)";
64 bool ok = bot.sendMessage(CHAT_ID, text);
65 Serial.println(ok ? "Mesaj gitti / sent" : "Mesaj gitmedi / failed");
66 } else {
67 Serial.println("Wi-Fi baglanamadi / no Wi-Fi");
68 }
69 WiFi.disconnect(true);
70 WiFi.mode(WIFI_OFF);
71 }
72 goToSleep(); // her durumda yeniden uyu / always sleep again
73}
74
75void loop() {
76 // buraya hiç gelinmez / never reached
77}
78The key idea of the code is the waitingForClose variable. Variables marked with RTC_DATA_ATTR aren't erased in deep sleep. Right before sleeping, the ESP32 checks the lid: if it's open, the pin is already LOW, and if we said wake on LOW, the chip would wake again immediately and fall into a loop that drains the battery in minutes. So with the lid open the wake level becomes HIGH; when the lid closes, the ESP32 quietly wakes and goes back to sleep waiting for the next opening. A message is sent only when the wake-up came from an opening; even if the postman closes the lid within half a second, the wake-up has already been triggered, so no notification is lost. The RSSI value in the message lets you monitor the signal strength at the mailbox remotely.
E-mail notification instead of Telegram
If you don't use Telegram, you can send an e-mail with the same logic. For this the ESP32 connects securely to an SMTP server; the most practical way is a Gmail account. Gmail won't let you sign in with your normal password: you need to enable two-step verification on the account and create an app password. The library is ESP Mail Client from the Library Manager. E-mail has one downside: the TLS handshake and the SMTP conversation take longer than Telegram, so the ESP32 stays awake about 2–4 seconds longer for each notification.
| Setting | Gmail value | Note |
|---|---|---|
| SMTP server | smtp.gmail.com | smtp.office365.com for Outlook |
| Port | 465 (SSL) or 587 (STARTTLS) | The code uses 465 |
| User | Your full Gmail address | Must match the sender address |
| Password | 16-character app password | Your account password won't work |
| Recipient | Any address | You can add several addRecipient calls |
1// Posta kutusu: kapak açılınca e-posta gönder (ESP Mail Client)
2// Mailbox: send an e-mail when the lid opens (ESP Mail Client)
3#include <WiFi.h>
4#include <ESP_Mail_Client.h>
5#include "driver/rtc_io.h"
6
7const char* WIFI_SSID = "AgAdi";
8const char* WIFI_PASS = "Sifre123";
9#define SMTP_HOST "smtp.gmail.com"
10#define SMTP_PORT 465 // SSL
11#define SENDER_EMAIL "[email protected]"
12#define SENDER_APP_PASSWORD "abcdabcdabcdabcd" // 16 haneli uygulama şifresi / 16-character app password
13#define RECIPIENT_EMAIL "[email protected]"
14
15const gpio_num_t REED_PIN = GPIO_NUM_33;
16RTC_DATA_ATTR uint32_t mailCount = 0;
17RTC_DATA_ATTR bool waitingForClose = false;
18
19SMTPSession smtp;
20
21bool sendMail(const String& body) {
22 Session_Config config;
23 config.server.host_name = SMTP_HOST;
24 config.server.port = SMTP_PORT;
25 config.login.email = SENDER_EMAIL;
26 config.login.password = SENDER_APP_PASSWORD;
27 config.login.user_domain = "127.0.0.1";
28 config.time.ntp_server = "pool.ntp.org"; // e-posta tarihi için saat / clock for the mail date
29 config.time.gmt_offset = 3; // Türkiye UTC+3 / Turkey UTC+3
30 config.time.day_light_offset = 0;
31
32 SMTP_Message message;
33 message.sender.name = "Posta Kutusu";
34 message.sender.email = SENDER_EMAIL;
35 message.subject = "Posta geldi / You've got mail";
36 message.addRecipient("Ben", RECIPIENT_EMAIL);
37 message.text.content = body;
38 message.text.charSet = "utf-8";
39
40 if (!smtp.connect(&config)) return false;
41 return MailClient.sendMail(&smtp, &message); // gönderir ve oturumu kapatır / sends and closes
42}
43
44void goToSleep() {
45 bool open = digitalRead(REED_PIN) == LOW;
46 waitingForClose = open;
47 rtc_gpio_pullup_dis(REED_PIN);
48 rtc_gpio_pulldown_dis(REED_PIN);
49 esp_sleep_enable_ext0_wakeup(REED_PIN, open ? 1 : 0);
50 esp_deep_sleep_start();
51}
52
53void setup() {
54 Serial.begin(115200);
55 rtc_gpio_deinit(REED_PIN);
56 pinMode(REED_PIN, INPUT);
57 delay(50);
58
59 if (esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_EXT0 && !waitingForClose) {
60 mailCount++;
61 WiFi.mode(WIFI_STA);
62 WiFi.begin(WIFI_SSID, WIFI_PASS);
63 unsigned long start = millis();
64 while (WiFi.status() != WL_CONNECTED && millis() - start < 10000) delay(100);
65 if (WiFi.status() == WL_CONNECTED) {
66 bool ok = sendMail("Posta kutusunun kapagi acildi. Sayac: " + String(mailCount));
67 Serial.println(ok ? "E-posta gitti / mail sent" : smtp.errorReason());
68 }
69 WiFi.mode(WIFI_OFF);
70 }
71 goToSleep();
72}
73
74void loop() {
75}
76Sleep current and battery life table
What sets battery life isn't so much the few seconds the ESP32 spends awake as the current it draws while asleep. On popular DevKit boards, the USB-serial converter, the AMS1117 regulator and the power LED keep drawing current even while the ESP32 sleeps; these boards use 1–10 mA in deep sleep. The same software runs at 10–50 µA on a board designed for low power (such as FireBeetle or TinyPICO) or on a bare ESP32 module. The difference is a hundred to a thousand times and moves battery life from days to years. To try the values with your own battery, use the battery life calculator.
| State | Typical current | Duration |
|---|---|---|
| Deep sleep, bare module / low-power board | 10–15 µA | Almost all day |
| 1 MΩ pull-down + LDO quiescent current | 3.3 µA + 2–5 µA | Always |
| Deep sleep, ordinary DevKit board | 1–10 mA | Always (the root of the problem) |
| Wi-Fi connection + Telegram (HTTPS) | Average 100–130 mA, peaks 300+ mA | 3–6 s |
| Wi-Fi + e-mail (SMTP, TLS) | Average 100–130 mA | 5–9 s |
| Single ESP-NOW packet | About 100 mA | 0.2–0.4 s |
| Scenario (4 openings a day, 2000 mAh usable) | Sleep share / day | Wake share / day | Estimated life |
|---|---|---|---|
| DevKit board + Telegram | About 120 mAh (5 mA) | About 0.7 mAh | About 16 days |
| Low-power board + Telegram | About 0.5 mAh (22 µA) | About 0.7 mAh | 4.5 years on paper, 1.5–2 years in practice |
| Low-power board + e-mail | About 0.5 mAh | About 1.2 mAh | 3 years on paper, 1.5 years in practice |
| Low-power board + ESP-NOW | About 0.5 mAh | About 0.03 mAh | Limited by the battery's self-discharge |
Let's see how the math works in a few lines. If a Telegram notification takes 5 seconds at an average of 120 mA, it uses 5 x 120 / 3600 = 0.17 mAh; four openings a day make 0.67 mAh. On the sleep side, 15 µA for the module, 3.3 µA for the resistor and about 4 µA for the regulator make 22 µA in total; 0.53 mAh in 24 hours. At 1.2 mAh a day, 2000 mAh lasts about 1,650 days, or 4.5 years. In reality a Li-ion cell self-discharges 2–3 percent a month and loses capacity in cold weather, so 1.5–2 years is a realistic target. For the cell's specs and safe use, see the 18650 battery guide.

Wi-Fi signal in a metal mailbox
- A metal box acts like a Faraday cage and weakens the signal by 10–30 dB. Look at the RSSI value in the message: -70 dBm or better is good, -80 dBm is borderline, at -85 dBm and below the connection drops.
- Place the ESP32 right behind the box's plastic lid, the name plate window or the letter slot; keep the antenna side at least 1 cm from the metal wall.
- Use an ESP32-WROOM-32U module with an external antenna connector and route the antenna out of the box through a small hole with a short u.FL cable.
- To shorten the connection time, use a static IP and give the router's channel and BSSID with WiFi.begin(ssid, pass, channel, bssid); this saves 1–2 seconds per notification.
- If the signal is still weak, plug a Wi-Fi repeater into a socket near the door or switch to the ESP-NOW solution in the next section. For general connection problems see the ESP32 Wi-Fi not connecting guide.
ESP-NOW and an indoor gateway for long range
If the mailbox is at the garden gate and Wi-Fi barely reaches it, there's a better way: the ESP32 in the mailbox never joins the Wi-Fi network and only sends an ESP-NOW packet to a second ESP32 inside the house. Because ESP-NOW needs no router association, no IP address and no TLS, the packet leaves within the first second after waking; the ESP32 stays awake 0.2–0.4 seconds instead of 3–6 seconds, and battery use drops to a twentieth. Range in open air is usually better than Wi-Fi too, because a single short packet can get through even with a weak signal. The gateway at home stays on with a USB adapter, receives the packet and forwards it to Telegram. For protocol details see the ESP-NOW guide.
1// Posta kutusu vericisi: ESP-NOW ile ağ geçidine tek paket (Wi-Fi'ye bağlanmaz)
2// Mailbox sender: one ESP-NOW packet to the gateway (no Wi-Fi connection)
3#include <WiFi.h>
4#include <esp_now.h>
5#include <esp_wifi.h>
6#include <esp_idf_version.h>
7#include "driver/rtc_io.h"
8
9uint8_t gatewayMac[] = {0x24, 0x6F, 0x28, 0xAA, 0xBB, 0xCC}; // ağ geçidinin STA MAC'i / gateway STA MAC
10const uint8_t WIFI_CHANNEL = 6; // ağ geçidi seri monitörde yazar / printed by the gateway
11const gpio_num_t REED_PIN = GPIO_NUM_33;
12
13typedef struct __attribute__((packed)) { // iki kartta aynı olmalı / must match on both boards
14 uint32_t count; // açılma sayısı / number of openings
15 uint8_t attempt; // kaçıncı deneme / attempt number
16} MailPacket;
17
18RTC_DATA_ATTR uint32_t mailCount = 0;
19RTC_DATA_ATTR bool waitingForClose = false;
20volatile bool sendDone = false;
21volatile bool delivered = false;
22
23#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
24void onSent(const esp_now_send_info_t *info, esp_now_send_status_t status) { // çekirdek 3.3+ / core 3.3+
25#else
26void onSent(const uint8_t *mac, esp_now_send_status_t status) { // çekirdek 2.x-3.2 / core 2.x-3.2
27#endif
28 delivered = (status == ESP_NOW_SEND_SUCCESS); // alıcı onay verdi mi? / did the receiver ACK?
29 sendDone = true;
30}
31
32bool sendPacket() {
33 WiFi.mode(WIFI_STA);
34 esp_wifi_set_channel(WIFI_CHANNEL, WIFI_SECOND_CHAN_NONE); // ağ geçidiyle aynı kanal / same channel
35 if (esp_now_init() != ESP_OK) return false;
36 esp_now_register_send_cb(onSent);
37
38 esp_now_peer_info_t peer = {};
39 memcpy(peer.peer_addr, gatewayMac, 6);
40 peer.channel = WIFI_CHANNEL;
41 peer.ifidx = WIFI_IF_STA;
42 if (esp_now_add_peer(&peer) != ESP_OK) return false;
43
44 MailPacket packet = {mailCount, 0};
45 for (uint8_t i = 1; i <= 3; i++) { // en fazla 3 deneme / up to 3 attempts
46 packet.attempt = i;
47 sendDone = false;
48 esp_now_send(gatewayMac, (uint8_t *)&packet, sizeof(packet));
49 unsigned long start = millis();
50 while (!sendDone && millis() - start < 100) delay(1);
51 if (delivered) return true;
52 delay(20);
53 }
54 return false;
55}
56
57void goToSleep() {
58 bool open = digitalRead(REED_PIN) == LOW;
59 waitingForClose = open;
60 rtc_gpio_pullup_dis(REED_PIN);
61 rtc_gpio_pulldown_dis(REED_PIN);
62 esp_sleep_enable_ext0_wakeup(REED_PIN, open ? 1 : 0);
63 esp_deep_sleep_start();
64}
65
66void setup() {
67 Serial.begin(115200);
68 rtc_gpio_deinit(REED_PIN);
69 pinMode(REED_PIN, INPUT);
70 delay(20);
71 if (esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_EXT0 && !waitingForClose) {
72 mailCount++;
73 Serial.println(sendPacket() ? "Teslim edildi / delivered" : "Teslim edilemedi / not delivered");
74 esp_now_deinit();
75 WiFi.mode(WIFI_OFF);
76 }
77 goToSleep();
78}
79
80void loop() {
81}
821// Ev içi ağ geçidi: ESP-NOW paketini al, Telegram'a ilet (USB adaptörle sürekli açık)
2// Indoor gateway: receive the ESP-NOW packet, forward it to Telegram (always on, USB powered)
3#include <WiFi.h>
4#include <WiFiClientSecure.h>
5#include <UniversalTelegramBot.h>
6#include <esp_now.h>
7#include <esp_idf_version.h>
8
9const char* WIFI_SSID = "AgAdi";
10const char* WIFI_PASS = "Sifre123";
11#define BOT_TOKEN "1234567890:AAExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
12#define CHAT_ID "123456789"
13
14typedef struct __attribute__((packed)) { // vericiyle aynı yapı / same struct as the sender
15 uint32_t count;
16 uint8_t attempt;
17} MailPacket;
18
19WiFiClientSecure client;
20UniversalTelegramBot bot(BOT_TOKEN, client);
21volatile bool newMail = false;
22volatile uint32_t lastCount = 0;
23uint32_t reportedCount = 0;
24
25#if ESP_IDF_VERSION_MAJOR >= 5
26void onReceive(const esp_now_recv_info_t *info, const uint8_t *data, int len) { // çekirdek 3.x / core 3.x
27#else
28void onReceive(const uint8_t *mac, const uint8_t *data, int len) { // çekirdek 2.x / core 2.x
29#endif
30 if (len != sizeof(MailPacket)) return;
31 MailPacket p;
32 memcpy(&p, data, sizeof(p));
33 lastCount = p.count;
34 newMail = true; // Telegram'ı loop'ta gönder / send Telegram in loop
35}
36
37void setup() {
38 Serial.begin(115200);
39 WiFi.mode(WIFI_STA);
40 WiFi.setSleep(false); // güç tasarrufu paket kaçırtır / power save drops packets
41 WiFi.begin(WIFI_SSID, WIFI_PASS);
42 while (WiFi.status() != WL_CONNECTED) delay(200);
43 Serial.print("MAC: ");
44 Serial.println(WiFi.macAddress()); // bunu vericiye yaz / put this into the sender
45 Serial.print("Kanal / channel: ");
46 Serial.println(WiFi.channel()); // vericideki WIFI_CHANNEL / WIFI_CHANNEL in the sender
47
48 client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
49 if (esp_now_init() != ESP_OK) {
50 Serial.println("ESP-NOW baslatilamadi / ESP-NOW init failed");
51 return;
52 }
53 esp_now_register_recv_cb(onReceive);
54}
55
56void loop() {
57 if (newMail) {
58 newMail = false;
59 uint32_t count = lastCount;
60 if (count != reportedCount) { // tekrar denemeleri ele / filter out retries
61 reportedCount = count;
62 bot.sendMessage(CHAT_ID, "Posta kutusu acildi / Mailbox opened (#" + String(count) + ")");
63 }
64 }
65 if (WiFi.status() != WL_CONNECTED) WiFi.reconnect();
66 delay(10);
67}
68The setup order is: first upload the gateway code to the ESP32 at home and note the MAC address and channel number printed in the Serial Monitor. Write these two values into the gatewayMac and WIFI_CHANNEL lines of the mailbox code and upload it to the sender. An ESP-NOW packet only arrives if both boards are on the same channel; if your router changes channels automatically, picking a fixed channel (1, 6 or 11) in the router settings solves this for good. The sender tries each packet up to three times and waits for the receiver's delivery acknowledgement; the gateway filters repeats with the same counter, so one opening gives one message. The WiFi.setSleep(false) line on the gateway matters: with Wi-Fi power saving on, the radio switches off at intervals and short ESP-NOW packets can be missed. Because the callback signatures changed between ESP32 core 2.x and 3.x, the code has an #if branch that fits both versions.
Common problems and fixes
| Problem | Cause | Fix |
|---|---|---|
| The ESP32 keeps waking and sleeping | Waking on LOW while the lid is open | Use the waitingForClose logic in the code |
| False alerts in the wind | The reed opens briefly when the lid rattles | Move the magnet closer, add a light spring to the lid or require 300 ms open in the code |
| It never wakes up | The pin isn't an RTC GPIO or the reed is wired wrong | Use GPIO 33 and check with a multimeter that the reed is closed when the lid is closed |
| The battery dies in a few days | The DevKit's regulator and USB chip | Switch to a low-power board, remove the power LED |
| Messages sometimes don't arrive | Weak Wi-Fi or a timeout | Watch the RSSI, move the antenna outside, switch to ESP-NOW |
| The board resets while connecting | Voltage drop at the Wi-Fi current peak | 470–1000 µF capacitor on the LDO output |
| It stops working in winter | Li-ion struggles to discharge below 0 °C | LiFePO4 cell or insulation inside the box |
Ideas to extend it
- Put a second reed on the back door where you collect the mail; watch both pins with ext1 wake-up and report "mail waiting" and "mail collected" separately.
- Wake once a day with the timer and send the battery voltage, so you know when to charge before it runs flat.
- Top up the battery with a small solar panel and a TP4056; for panel sizing see the solar-powered sensor guide.
- Connect the gateway to Home Assistant and announce the notification on a smart speaker at home.
- Adapt the same logic to a door, window or cupboard sensor; for a doorbell see the ESP32 smart doorbell guide.
A reed switch, deep sleep and a single notification: combined the right way, these three turn a mailbox sensor into a device that runs on its own for years. If you want to try a reed switch door sensor, ESP32 deep sleep and sending a motion alert to Telegram step by step with a circuit diagram and code, have a look at the related projects in the BlueGrays app; put those parts together and you've built this whole mailbox system.
Frequently asked questions
How long does an ESP32 mailbox sensor last on a battery?
With a low-power ESP32 board drawing 10–50 µA in sleep and an 18650 cell, it lasts 1.5–2 years in practice with a few notifications a day. An ordinary DevKit board draws milliamps even in sleep and empties the same cell in two or three weeks. With ESP-NOW the awake time is shorter, so battery life gets even longer.
Which pin can wake an ESP32 from deep sleep?
ext0 and ext1 wake-up only work on RTC GPIO pins: 0, 2, 4, 12–15, 25–27 and 32–39. GPIO 32, 33, 25, 26 or 27 are the safest choices because they don't affect booting. Use ext0 for a single pin and ext1 for several pins.
What is the best sensor for a mailbox notifier?
A reed switch is the best because it's a passive switch that uses no power at all, and together with a magnet it costs very little. An infrared obstacle sensor or a distance sensor can detect the letter itself, but they draw current all the time and don't last long on a battery. A microswitch also works but corrodes outdoors over time.
Can an ESP32 connect to Wi-Fi inside a metal mailbox?
It can, but a metal box weakens the signal by 10–30 dB. Placing the ESP32 behind the plastic lid or the letter slot, using an ESP32-WROOM-32U with an external antenna or adding a repeater near the door is usually enough. If that fails, sending a packet to a gateway at home via ESP-NOW is the most robust way.
How do I send an e-mail from an ESP32 with Gmail?
Turn on two-step verification in your Gmail account and create an app password; the ESP32 uses this 16-character password to connect to smtp.gmail.com on port 465. In the Arduino IDE, install the ESP Mail Client library and set the sender, recipient, subject and text. Your normal account password won't work for SMTP login.
What is the range of ESP-NOW?
In open air you usually get 100–200 meters between two ESP32 boards with onboard antennas, and more with external antennas. Walls, trees and a metal box shorten that distance. Its advantage over Wi-Fi is that a single short packet can get through even with a weak signal, and there's no time spent connecting to a router.
Projects to build after reading this
See all projects
Reading a Reed Switch
Ever wondered about the magnetic switch inside door and window alarms? When a magnet comes near the reed relay module, the tiny switch inside it closes; the Arduino reads it once a second and prints…

Reed Switch Door Sensor
Tell whether your door is open or closed just by looking at a light. You attach a small magnet to the door and a magnet-sensing switch to the frame; when the door is closed they sit side by side and…

ESP32 Deep Sleep — Battery Saving (OLED + RTC RAM Counter)
The ESP32's Deep Sleep mode shuts down the CPU and most peripherals, cutting current draw to about 10µA, which is vital for battery-powered IoT devices. This project uses three wake-up sources: a timer (15 s), an external pin (EXT0, the button on GPIO 33) and a touch pin (T0/GPIO 4). Counters marked with RTC_DATA_ATTR survive deep sleep.

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.

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.

Automatic Lighting with the ESP32 PIR Motion Sensor
In this project an HC-SR501 PIR motion sensor detects someone entering the room and turns on an LED automatically. millis() tracks how long the LED stays on: each HIGH reading refreshes the last-motion time, and the LED turns off at least 10 seconds after the last HIGH. The code also waits 50 ms with delay(50) in every loop, so the loop is not fully non-blocking. Great for stairs, hallways, bathrooms or closet lighting.

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.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

