Skip to Content

← All functionalities

Geotechnical slope monitoringServer (Node-RED)SMTPAlerts

Email alerts with smtplib and a Gmail app password

When a remote concentrator reboots or a sensor crosses its threshold, someone has to know within minutes. These SMTP email alerts use nothing beyond Python's standard library: smtplib with STARTTLS against smtp.gmail.com and a Gmail app password. The script comes from a real slope monitoring deployment, where it reports restarts of the Raspberry Pi concentrator and forwards level 3-4 alarms detected by Node-RED across four ESP32 PLC 14 Ethernet stations.

Two modes, one script

Called with two arguments it sends any subject and body — that is how Node-RED's exec node forwards classified alarms. Called with no arguments it sends a standard restart notice with hostname and timestamp, which makes it ideal for a cron @reboot entry. One file covers both the planned alerts and the unplanned ones.

App passwords, not your real password

Gmail blocks plain password logins from scripts. With 2-step verification enabled you generate a 16-character app password that only works for SMTP and can be revoked without touching the account. In the code it is the APP_PASSWORD placeholder; in production it loads from an environment variable, never from the repository.

Headers that survive spam filters

The message is built with MIMEText and explicit Subject, From and To headers, UTF-8 encoded. Automated emails without proper headers are the first thing spam filters drop — and a monitoring alert that lands in spam is worse than no alert, because everyone believes it was sent.

A snippet from the implementation

Straight from the example as deployed on the Server (Node-RED) — copy it freely:

def build_message(subject, body):
    """Builds the MIMEText with full headers to avoid spam filters."""
    message = MIMEText(body, "plain", "utf-8")
    message["Subject"] = subject
    message["From"] = EMAIL_SENDER
    message["To"] = EMAIL_RECEIVER
    return message

The full example is a complete program — wiring header, setup and main loop — ready to adapt to your application.

Frequently asked questions

Why email instead of a messaging app or SMS?

Email needs no extra service, no SIM and no API contract, and the support inbox is already monitored. For higher criticality you can add channels later, keeping SMTP as the baseline that always works.

Does this work with providers other than Gmail?

Yes. Any SMTP server with STARTTLS on port 587 works — change SMTP_HOST and the credentials. Gmail with an app password is simply a convenient, reliable default for small deployments.

How does Node-RED trigger the alarm emails?

The polling flow classifies each station reading into levels 0-4. Levels 3 and 4 route to a function that formats subject and body, then an exec node runs this script with both as arguments.

Related functionalities