We use email alerts to get notified quickly when a sensor detects something important. This helps us act fast without watching the sensor all the time.
Email alerts on sensor thresholds in Raspberry Pi
import smtplib from email.mime.text import MIMEText # Set sensor threshold THRESHOLD = 30 # Function to send email alert def send_email_alert(sensor_value): sender = 'your_email@example.com' receiver = 'receiver_email@example.com' password = 'your_email_password' subject = 'Sensor Alert' body = f'Sensor value reached {sensor_value}, which is above the threshold.' msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: server.login(sender, password) server.sendmail(sender, receiver, msg.as_string()) # Example sensor reading sensor_value = 35 if sensor_value > THRESHOLD: send_email_alert(sensor_value)
Replace your_email@example.com, receiver_email@example.com, and your_email_password with your actual email details.
This example uses Gmail's SMTP server with SSL on port 465.
if sensor_value > THRESHOLD:
send_email_alert(sensor_value)def send_email_alert(sensor_value): # email setup and sending code here pass
This program checks if the sensor value is above the threshold. If yes, it prints a message about sending an alert email. The actual email sending line is commented out to avoid accidental emails during testing.
import smtplib from email.mime.text import MIMEText THRESHOLD = 30 def send_email_alert(sensor_value): sender = 'your_email@example.com' receiver = 'receiver_email@example.com' password = 'your_email_password' subject = 'Sensor Alert' body = f'Sensor value reached {sensor_value}, which is above the threshold.' msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: server.login(sender, password) server.sendmail(sender, receiver, msg.as_string()) sensor_value = 35 if sensor_value > THRESHOLD: print(f"Sensor value {sensor_value} is above threshold {THRESHOLD}. Sending alert email...") # Uncomment the next line to actually send the email # send_email_alert(sensor_value) else: print(f"Sensor value {sensor_value} is within safe limits.")
Make sure to enable 'less secure app access' or use an app password if using Gmail.
Test your email sending code carefully to avoid spamming yourself.
You can replace the sensor_value with real sensor readings from your Raspberry Pi.
Email alerts help you get notified instantly when sensor values cross limits.
You write a function to send emails using SMTP and call it when needed.
Always test with print statements before sending real emails.