Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Monitor the raspberry pi temperature and send an email/shutdown in case it's too high
# coding=utf-8
import os
import smtplib
from email.mime.text import MIMEText
critical = False
high = 60
too_high = 80
# At First we have to get the current CPU-Temperature with this defined function
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
# Now we convert our value into a float number
temp = float(getCPUtemperature())
# Check if the temperature is abouve 60°C (you can change this value, but it shouldn't be above 70)
if (temp > high):
if temp > too_high:
critical = True
subject = "Critical warning! The temperature is: {} shutting down!!".format(temp)
body = "Critical warning! The actual temperature is: {} \n\n Shutting down the pi!".format(temp)
else:
subject = "Warning! The temperature is: {} ".format(temp)
body = "Warning! The actual temperature is: {} ".format(temp)
# Enter your smtp Server-Connection
server = smtplib.SMTP('localhost', 25) # if your using gmail: smtp.gmail.com
server.ehlo()
server.starttls()
server.ehlo
# Login
# server.login("your email or username", "your Password")
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = "Root"
msg['To'] = "root"
# Finally send the mail
server.sendmail("root", "root", msg.as_string())
server.quit()
# Critical, shut down the pi
if critical:
os.popen('sudo halt')
# Don't print anything otherwise.
# Cron will send you an email for any command that returns "any" output (so you would get another email)
# else:
# print "Everything is working fine!"
@LeonardoGentile
Copy link
Author

LeonardoGentile commented Oct 28, 2016

Originally from https://quaintproject.wordpress.com/2013/09/14/alert-mail-raspberry-pi/
I've tweaked it a little bit to also shutdown the pi in case temp is too high (80'C in my case).

To make this as a cronjob running every 30 min do this

mkdir -p ~/scripts
vi ~/scripts/temp.py

paste the code from the script above.

Then crontab -e and add this:

30 * * * * python ~/scripts/temp.py

close crontab editor (ctrl-x if nano or esc, then :wq if vim)

That's it

@r4pt0r66
Copy link

r4pt0r66 commented Dec 24, 2018

Awesome!

I modified with code from https://stackoverflow.com/questions/17541044/how-can-i-make-the-python-program-to-check-linux-services to shutdown and start services depending on the temp.

@jolimk
Copy link

jolimk commented Jun 15, 2019

Hi, sorry to bother Im a noob. Where exactly do you input your SMTP server, email, and password? Im using gmail. Thank you for your help.

@netbob
Copy link

netbob commented Nov 16, 2020

you would modify these lines of code:

server = smtplib.SMTP('smtp.gmail.com', 587) # if you're using gmail: smtp.gmail.com
server.ehlo()
server.starttls()
server.ehlo
# Login
server.login("user@gmail.com", "your Password")
I know this reply is late.
Nb

@netbob
Copy link

netbob commented Nov 16, 2020

This is a pretty nice little tool for monitoring devices. Nice work
Nb

@StoneMcYT
Copy link

StoneMcYT commented Jan 3, 2021

im confused on how this thing even sends a email to me so do i just run the py file then it works? Also can you add maybe a configuration turorial

@Chebattler
Copy link

Chebattler commented Apr 19, 2021

im confused on how this thing even sends a email to me so do i just run the py file then it works? Also can you add maybe a configuration turorial

1)As stated, change this line
server = smtplib.SMTP('smtp.gmail.com', 587) # if you're using gmail: smtp.gmail.com
With your smtp server. you can google it if it is not gmail.

2)Next change login and password as stated
server.login("user@gmail.com", "your Password")

  1. change
    msg['From'] = "Root" // to actual FROM email address
    msg['To'] = "root" // and actual TO email address , example: blabla@gmail.com
    Because many smtp servers ask for actual address.
  2. Next, change line: server.sendmail("root", "root", msg.as_string())
    to:
    server.sendmail(msg['From'], msg['To'], msg.as_string())
    This should be enough, hope it helps.

LeonardoGentile, thanks very much for the script. Works perfectly.

@LeonardoGentile
Copy link
Author

LeonardoGentile commented Apr 19, 2021

I often forget I wrote this little script, I'm glad it's useful for someone else : ] 👍

@degupukas
Copy link

degupukas commented Mar 23, 2022

hi, someone can help me
this is the code

# Enter your smtp Server-Connection
server = smtplib.SMTP('smtp.zoho.com', 465) # if your using gmail: smtp.gmail.com
server.ehlo()
server.starttls()
server.ehlo
# Login
server.login("degu@zoho.com", "mypass")

msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = "degu@zoho.com"
msg['To'] = "degu@zoho.com"

# Finally send the mail
server.sendmail(msg['from'],msg['To'], msg.as_string())
server.quit()

# Critical, shut down the pi
if critical:
    os.popen('sudo halt')

ERROR

Traceback (most recent call last):
File "ubi.py", line 29, in
server = smtplib.SMTP('smtp.zoho.com', 465) # if your using gmail: smtp.gmail.com
File "/usr/lib/python3.7/smtplib.py", line 251, in init
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.7/smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "/usr/lib/python3.7/smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

@paradonym
Copy link

paradonym commented Mar 26, 2022

What's the difference between 30 * * * * python ~/scripts/temp.py and */30 * * * * python ~/scripts/temp.py?
My crontabs always had */30 to define "every 30th..."

@MestreLion
Copy link

MestreLion commented May 25, 2022

@paradonym

What's the difference between 30 * * * * python ~/scripts/temp.py and */30 * * * * python ~/scripts/temp.py? My crontabs always had */30 to define "every 30th..."

30 means "at minute 30", so it only runs once every hour, while */30 means "on every 30 minutes", running twice every hour, at minutes 0 and 30.

See https://crontab.guru/

@Ricknanon
Copy link

Ricknanon commented Jul 23, 2022

Thank you very much.
Worked like a charm !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment