So basically, I made a python script to send me an email containing my public IP every 12 hours. My goal is to make it automatically send an email only when my IP changes. I would love it if you guys could give me some help.
There's my code:
from json import loads
from urllib.request import urlopen
import time
import smtplib
while True:
data = loads(urlopen("http://httpbin.org/ip").read())
print ("The public IP is : %s" % data["origin"])
try:
server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server_ssl.ehlo()
server_ssl.login("[email protected]", "password")
msg = """From: Automated Python Script <[email protected]>
To: First Last <[email protected]>
Subject: SMTP e-mail test
""" + data["origin"] + """
"""
server_ssl.sendmail("[email protected]", "[email protected]", msg)
print ("Successfully sent email!")
time.sleep(720)
except SMTPException:
print ("Something went wrong...")
By the way, it's in python 3.
I'd really like it to send me an email automatically when my public ip changes instead of sending me an email with probably the same IP every 12 hours.
Thanks!
This checks the change in public ip to whichever time interval you want based on the value you set to x. If your public ip changes frequently then set lower values of x and if it changesless often you can set it accordingly
from json import loads
from urllib.request import urlopen
import time
import smtplib
data_prev = loads(urlopen("http://httpbin.org/ip").read())
prev_public = data_prev["origin"]
while True:
data_next = loads(urlopen("http://httpbin.org/ip").read())
next_public = data_next["origin"]
print ("The public IP is : %s" % data["origin"])
if(next_public != prev_public):
prev_publi = next_public
try:
server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server_ssl.ehlo()
server_ssl.login("[email protected]", "password")
msg = """From: Automated Python Script <[email protected]>
To: First Last <[email protected]>
Subject: SMTP e-mail test
""" + data["origin"] + """
"""
server_ssl.sendmail("[email protected]", "[email protected]", msg)
print ("Successfully sent email!")
time.sleep(x) # set x to whichever value you want
#time.sleep(720)
except SMTPException:
print ("Something went wrong...")