Practical case: mailbox alert with Raspberry Pi

Practical case: Raspberry Pi Mailbox Monitor — hero

Objective and use case

What you’ll build: A Raspberry Pi mailbox monitor that detects when the door opens with a magnetic reed switch, debounces the signal, logs the event with a timestamp, and sends a phone alert through ntfy.sh. It is a lightweight GPIO automation project with near-instant notification, typically under 1 second on a stable Wi‑Fi connection.

Why it matters / Use cases

  • Get a real-time alert when mail is delivered instead of checking the mailbox manually.
  • Reduce false triggers by debouncing switch input, useful for windy outdoor enclosures or vibrating metal doors.
  • Create a low-power home automation sensor with minimal compute load, often under 2% CPU and negligible GPU use on a Raspberry Pi.
  • Keep a local event history to verify delivery times, for example logging 10:14:32 mailbox-open events for packages or letters.
  • Use the same pattern for gate open alerts, shed access notifications, or cabinet-door monitoring.

Expected outcome

  • A working reed-switch circuit connected safely to Raspberry Pi GPIO with a pull-up or pull-down resistor.
  • Reliable open-event detection with debounce timing that filters brief contact bounce in milliseconds.
  • Push-style alerts delivered to your phone via ntfy.sh with typical end-to-end latency of about 0.5–2 seconds, depending on network quality.
  • Automatic startup at boot using systemd so monitoring resumes after power loss or reboot.
  • Local timestamped logs you can review for troubleshooting, delivery tracking, or missed-notification checks.

Audience: Raspberry Pi beginners, DIY home automation hobbyists, and students learning GPIO input handling; Level: Basic

Architecture/flow: Reed switch changes GPIO state when the mailbox door opens → Raspberry Pi script reads and debounces the input → event is logged locally → HTTP notification is sent to ntfy.sh → phone receives the alert.

Educational validation note

Before publication, this case passed the Prometeo automated validation gate with status PASS. The validator checked the code blocks, article structure, copy/paste-safe commands and consistency with the supported device catalog.

Published validation evidence

  • Automatic result: PASS.
  • Parsed structure: 3 sections, 3 tables and 14 code blocks detected before publication.
  • Checked code: 1 Python/py_compile, 1 service/config blocks, 10 Bash/copy-paste checks.
  • Supported catalog: the article text was checked against Prometeo’s validation-capable device profiles, and unsupported stacks block publication.
  • Report findings: no blocking findings.

This validation confirms syntax and tool compatibility for the published material, but it does not replace physical testing on your exact hardware, wiring and runtime environment.

Educational safety note

This project is an educational prototype, not a certified product. Before powering the setup, verify the pinout of your exact ULX3S board revision, keep FPGA I/O signals at 3.3 V, never connect 5 V directly to I/O pins, disconnect power before changing wiring, and use suitable external supplies for loads, motors or servos while sharing ground only when the wiring requires it.


title: Smart Mailbox Open Alert with Raspberry Pi
level: Basic
slug: practical-case-raspberry-pi


Smart Mailbox Open Alert with Raspberry Pi

This practical Raspberry Pi project builds a smart mailbox open alert.
A magnetic reed switch detects when the mailbox door opens, and the Raspberry Pi sends an alert to your phone using ntfy.sh.

Conceptual block diagram

High-level view: what enters the system, what each block processes, and what comes out.

Functional architecture

Reed switch changes GPIO state when the m…

Raspberry Pi script reads and debounces t…

event is logged locally

HTTP notification is sent to ntfy.sh

phone receives the alert

Conceptual signal and responsibility flow between device blocks.

Validation path

Source code

PlatformIO build

Flash

Serial monitor

Conceptual summary of the tools used to check the published material.

What this project does

  • Detects mailbox door state with a reed switch
  • Debounces the input to reduce false triggers
  • Sends a push-style network alert when the mailbox is opened
  • Logs each open event locally with a timestamp
  • Runs automatically at boot with systemd

Safety note
This project is for low-voltage GPIO only. Do not connect Raspberry Pi GPIO pins directly to mains voltage, powered doorbells, electric locks, or unknown wiring inside a metal mailbox. If the mailbox is outdoors, protect the Pi and wiring from moisture and use proper strain relief.

Parts

  • Raspberry Pi with network access
  • microSD card with Raspberry Pi OS
  • 1 magnetic reed switch, normally open
  • 1 x 10 kOhm resistor
  • Jumper wires
  • Breadboard or soldered prototype board

Wiring

The reed switch is used as a contact sensor. When the mailbox door opens, the switch changes state and the Raspberry Pi can trigger the smart mailbox open alert.

Pin table

FunctionComponent pinRaspberry Pi pin
3.3 V pull-up source10 kOhm resistor end 13.3 V, physical pin 1
Signal node10 kOhm resistor end 2 + reed switch end 1GPIO17, physical pin 11
Ground pathReed switch end 2GND, physical pin 6

Logic

Mailbox stateReed switchGPIO17 state
Closed, magnet near switchClosed contactLOW
Open, magnet away from switchOpen contactHIGH

This wiring uses an external pull-up resistor to 3.3 V. The GPIO reads:

  • 0 when the mailbox is closed
  • 1 when the mailbox is open

System setup

Update the system and install the required packages:

sudo apt update
sudo apt install -y python3 python3-gpiozero python3-requests

Create a project directory:

mkdir -p /home/pi/mailbox-alert

Python application

Save this file as /home/pi/mailbox-alert/mailbox_alert.py.

#!/usr/bin/env python3
from gpiozero import Button
from signal import pause
from datetime import datetime
import os
import socket
import requests

PIN = 17
LOG_FILE = "/home/pi/mailbox-alert/mailbox_events.log"
HOSTNAME = socket.gethostname()
TOPIC = f"{HOSTNAME}-smart-mailbox-open-alert"
NTFY_URL = f"https://ntfy.sh/{TOPIC}"

sensor = Button(PIN, pull_up=False, bounce_time=0.2)

def write_log(message: str) -> None:
    timestamp = datetime.now().isoformat(timespec="seconds")
    line = f"{timestamp} {message}\n"
    with open(LOG_FILE, "a", encoding="utf-8") as log_file:
        log_file.write(line)

def send_alert() -> None:
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    title = "Mailbox opened"
    body = f"Smart mailbox open alert from {HOSTNAME} at {now}"
    headers = {
        "Title": title,
        "Priority": "default",
        "Tags": "mailbox,postbox,package"
    }

    try:
        response = requests.post(
            NTFY_URL,
            data=body.encode("utf-8"),
            headers=headers,
            timeout=10
        )
        response.raise_for_status()
        write_log(f"ALERT_SENT topic={TOPIC} status={response.status_code}")
    except requests.RequestException as exc:
        write_log(f"ALERT_FAILED error={exc}")

def on_open() -> None:
    write_log("MAILBOX_OPEN")
    send_alert()

def main() -> None:
    write_log(f"START topic={TOPIC} pin={PIN}")
    sensor.when_pressed = on_open
    pause()

if __name__ == "__main__":
    os.makedirs("/home/pi/mailbox-alert", exist_ok=True)
    main()

Make it executable:

chmod +x /home/pi/mailbox-alert/mailbox_alert.py

Test the smart mailbox open alert manually

Run the application in a terminal:

python3 /home/pi/mailbox-alert/mailbox_alert.py

Then open the mailbox door. You should see a new event in the log file:

tail -f /home/pi/mailbox-alert/mailbox_events.log

Subscribe on your phone or another device to:

https://ntfy.sh/<your-hostname>-smart-mailbox-open-alert

For example, if your Raspberry Pi hostname is raspberrypi, the topic is:

https://ntfy.sh/raspberrypi-smart-mailbox-open-alert

You can check your hostname with:

hostname

Run at boot with systemd

Create /etc/systemd/system/mailbox-alert.service:

[Unit]
Description=Smart Mailbox Open Alert
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=pi
WorkingDirectory=/home/pi/mailbox-alert
ExecStart=/usr/bin/python3 /home/pi/mailbox-alert/mailbox_alert.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl daemon-reload
sudo systemctl enable mailbox-alert.service
sudo systemctl start mailbox-alert.service
sudo systemctl status mailbox-alert.service --no-pager

Validation method

To validate that this smart mailbox open alert works correctly:

  1. Start the service.
  2. Close the mailbox so the magnet is near the reed switch.
  3. Open the mailbox once.
  4. Confirm:
  5. one MAILBOX_OPEN entry appears in the local log
  6. one ALERT_SENT entry appears in the local log
  7. one notification arrives on the subscribed ntfy.sh topic
  8. Repeat 10 open/close cycles.

Expected evidence

CheckExpected result
GPIO detectionOne trigger when door opens
Local logTimestamped MAILBOX_OPEN and ALERT_SENT lines
Network alertOne notification per open event
RepeatabilityConsistent behavior across repeated open/close cycles

Troubleshooting

No alert arrives

Check that the Pi has internet access:

ping -c 3 ntfy.sh

Check the service logs:

journalctl -u mailbox-alert.service --no-pager -n 50

False triggers

  • Increase bounce_time from 0.2 to 0.5
  • Mount the magnet and reed switch more securely
  • Keep sensor wires short or twisted to reduce noise

Input never changes

Verify the GPIO state with:

python3 -c "from gpiozero import Button; from time import sleep; s=Button(17, pull_up=False); print(s.is_pressed); sleep(1)"

Result

You now have a smart mailbox open alert built on a Raspberry Pi.
When the mailbox door opens, the reed switch changes state, the Pi detects the event, and an alert is sent automatically.

Find this product and/or books on this topic on Amazon

Go to Amazon

As an Amazon Associate, I earn from qualifying purchases. If you buy through this link, you help keep this project running.

Quick Quiz

Question 1: What is the main device used to detect when the mailbox door opens?




Question 2: What service is used to send phone alerts in this project?




Question 3: What is the purpose of debouncing the switch input?




Question 4: On a stable Wi-Fi connection, how quickly are notifications typically delivered?




Question 5: What kind of event history does the system keep locally?




Question 6: Which Raspberry Pi feature is primarily used in this project?




Question 7: What is one benefit of this project in terms of resource usage?




Question 8: Which of these is another suggested use for the same monitoring pattern?




Question 9: What electrical component should be used with the reed-switch circuit for safe GPIO connection?




Question 10: What example timestamp is given for a logged mailbox-open event?




Carlos Núñez Zorrilla
Carlos Núñez Zorrilla
Electronics & Computer Engineer

Telecommunications Electronics Engineer and Computer Engineer (official degrees in Spain).

Follow me:
Scroll to Top