Skip to content

Instantly share code, notes, and snippets.

@mattbk
Forked from johnantoni/startup_mailer.py
Last active February 20, 2016 23:04
Show Gist options
  • Save mattbk/f2373c4996d9dace6693 to your computer and use it in GitHub Desktop.
Save mattbk/f2373c4996d9dace6693 to your computer and use it in GitHub Desktop.
Raspberry Pi - Send email with public IP address (will need Gmail account to send from. Need to allow less secure apps at Gmail, see http://naelshiab.com/tutorial-send-email-python/).
# https://gist.github.com/johnantoni/8199088
import subprocess
import smtplib
import socket
from email.mime.text import MIMEText
import datetime
# Change to your own account information
to = 'TO@gmail.com'
gmail_user = 'YOU@gmail.com'
gmail_password = 'PASSWORD'
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_network_ip = 'Network IP: %s' % ipaddr
#http://stackoverflow.com/a/9481595/2152245
from urllib2 import urlopen
my_public_ip = '\nPublic IP: %s' % urlopen('http://ip.42.pl/raw').read()
msg = MIMEText(my_network_ip+my_public_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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment