Skip to content

Instantly share code, notes, and snippets.

@johnantoni
Created December 31, 2013 16:21
Show Gist options
  • Save johnantoni/8199088 to your computer and use it in GitHub Desktop.
Save johnantoni/8199088 to your computer and use it in GitHub Desktop.
raspberry pi - send email on startup (will need gmail account to send from)
import subprocess
import smtplib
import socket
from email.mime.text import MIMEText
import datetime
# Change to your own account information
to = 'me@example.com'
gmail_user = 'test@gmail.com'
gmail_password = 'yourpassword'
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]
my_ip = 'Your ip is %s' % ipaddr
msg = MIMEText(my_ip)
msg['Subject'] = 'IP For RaspberryPi on %s' % today.strftime('%b %d %Y')
msg['From'] = gmail_user
msg['To'] = to
smtpserver.sendmail(gmail_user, [to], msg.as_string())
smtpserver.quit()
@nikmart
Copy link

nikmart commented Aug 23, 2016

@bereshr1, I just had this issue and needed to allow less secure devices to access gmail. You can look here for that setting: here

@yun14u
Copy link

yun14u commented Dec 19, 2016

found the solution and modified johnantoni's script. just tested and worked !

@TheMole3
Copy link

TheMole3 commented Dec 28, 2017

Hello! Sorry if i bring up this old thread but i get this error:

Traceback (most recent call last):
  File "/home/pi/code/startup_mailer.py", line 21, in <module>
    ipaddr = split_data[split_data.index('src')+1]
ValueError: 'src' is not in list

Any idea of how to fix it?

@ChristopherLu
Copy link

The 'src' is not in list is caused by python3. Try python2 instead.

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