Raspberry PI – sending emails on boot
How to send a boot email from your Raspberry PI?
Let your Raspberry PI automatically send you an email with it’s current IP-address whenever it starts. Very handy for Remote Desktops or SSH connections and such!
- create a Python script, for instance ‘/home/pi/Code/startup_mailer.py’
sudo mkdir /home/pi/Code
sudo nano /home/pi/Code/startup_mailer.py
- Paste the following code in the new file and replace the red text with your own data:
import subprocess
import smtplib
import socket
import os
from email.mime.text import MIMEText
import datetime
# Change to your own account information
to = ‘‘
gmail_user = ‘‘
gmail_password = ‘mygmailpassword‘
smtpserver = smtplib.SMTP(‘smtp.gmail.com’, 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_password)
today = datetime.date.today()
# Very Linux Specific
arg=’ip route list’
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate()
split_data = data[0].split()
ipaddr = split_data[split_data.index(‘src’)+1]
# Get the current CPU speed
f = os.popen(‘/opt/vc/bin/vcgencmd get_config arm_freq’)
cpu = f.read()
mail_body = “CPU speed: ” + cpu + “IP address: %s” % ipaddr
msg = MIMEText(mail_body)
msg[‘Subject’] = “RasPI @ “+ipaddr+” started up on %s” % today.strftime(‘%b %d %Y’)
msg[‘From’] = gmail_user
msg[‘To’] = to
smtpserver.sendmail(gmail_user, [to], msg.as_string())
smtpserver.quit()
- make it automatically run whenever the RPi is booting:
sudo nano /etc/rc.local - add a new line:
if [ “$_IP” ]; then
printf “My IP address is %s\n” “$_IP”
python /home/pi/Code/startup_mailer.py
fi