Robert Cudmore    archive    tags    search    software

Startup mailer on a Raspberry Pi

Have a Raspberry Pi send an email when it boots.

Before doing this you need to setup a gmail account to send email from. You will need to reduce the security on this account so please do not use your primary gmail account, set up a new one.

Reduce the security on this account

Make a python script.

mkdir code
cd code

Paste the following into the file

import subprocess
import smtplib
import socket
import os
from email.mime.text import MIMEText
import datetime
import sys
from time import strftime
import platform # to get host name

message = ''
if len( sys.argv ) > 1:
    message = sys.argv[1]

# list of email accounts to send to
to = ['send to email 1', 'send to email 2']

# Change to your own account information to send from
gmail_user = ''
gmail_password = 'your_gmail_password'

smtpserver = smtplib.SMTP('', 587)
smtpserver.login(gmail_user, gmail_password)

# get ip and router address
arg='ip route list'
data = p.communicate()
split_data = data[0].split()

ipaddr = split_data[split_data.index('src')+1]
routerAddress = split_data[split_data.index('via')+1]

hostName = platform.node()

mail_body = 'name: ' + hostName + '\n'
mail_body += 'IP: %s\n' % ipaddr
mail_body += 'router: %s\n' % routerAddress
mail_body += 'message: ' + message + '\n'

timeStr = strftime('%b %d %Y, %H:%M:%S')

mail_subject = hostName + ' pi@' + ipaddr + ' on %s' % timeStr

msg = MIMEText(mail_body)
msg['Subject'] = mail_subject
msg['From'] = gmail_user
smtpserver.sendmail(gmail_user, to, msg.as_string())

Have the python script run at boot

# make it executable
chmod +x code/ 

# edit crontab
crontab -e

Append this line to crontab, ‘boot’ is a message to send.

@reboot (sleep 10; /home/pi/code/ 'boot')

I am using with my normal password

Tags: raspberry, linux

©2019. Robert Cudmore.