jmunsch

ip_mailer

Feb 7th, 2014
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. import httplib
  2. import string
  3. import time
  4. import smtplib
  5. from email.MIMEMultipart import MIMEMultipart
  6. from email.MIMEBase import MIMEBase
  7. from email.MIMEText import MIMEText
  8. from email import Encoders
  9. import os
  10.  
  11.  
  12. def get_ip():
  13.     # http://imagineerblogs.wordpress.com/2011/09/26/python-script-for-find-your-current-external-ip/
  14.     conn = httplib.HTTPConnection("checkip.dyndns.org")
  15.     conn.request("GET","/index.html")
  16.     r1 = conn.getresponse()
  17.     conn.close()
  18.     if r1.status == 200:
  19.       data1 = r1.read()
  20.     else:
  21.       print 'Error connecting to the server!! Check your internet connection'
  22.       exit()
  23.     startstr = string.find(data1,': ')+2
  24.     endstr = string.find(data1,'</b')
  25.     return data1[startstr:endstr]
  26.  
  27.  
  28. def email_me(current):
  29.  
  30.     current = current
  31.     gmail_user = "[email protected]"
  32.     gmail_pwd = "put_password_here"
  33.  
  34.     def mail(to, subject, text, attach):
  35.         msg = MIMEMultipart()
  36.      
  37.         msg['From'] = gmail_user
  38.         msg['To'] = to
  39.         msg['Subject'] = subject
  40.          
  41.         msg.attach(MIMEText(text))
  42.          
  43.         part = MIMEBase('application', 'octet-stream')
  44.         part.set_payload(open(attach, 'rb').read())
  45.         Encoders.encode_base64(part)
  46.         part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach))
  47.         msg.attach(part)
  48.          
  49.         mailServer = smtplib.SMTP("smtp.gmail.com", 587)
  50.         mailServer.ehlo()
  51.         mailServer.starttls()
  52.         mailServer.ehlo()
  53.         mailServer.login(gmail_user, gmail_pwd)
  54.         mailServer.sendmail(gmail_user, to, msg.as_string())
  55.         # Should be mailServer.quit(), but that crashes...
  56.         mailServer.close()
  57.  
  58.     this_str = str(current)+"\nWell well well. Am i going to put this code on github?"
  59.     mail("[email protected]","Updated Address",this_str,"/home/jmunsch/Desktop/BdCMUNGCMAAEi20.jpg")
  60.  
  61. current = get_ip()
  62. last = current
  63.  
  64. while True:
  65.     try:
  66.         current = get_ip()
  67.         if current is not last:
  68.             time_stamp = "\nip changed:"+time.ctime()
  69.             print time_stamp
  70.             email_me(current+time_stamp)
  71.             last = current
  72.         else:
  73.             time.sleep(600)
  74.     except Exception,e:
  75.         print(e)
Add Comment
Please, Sign In to add comment