我已经学习了几个月,现在正在尝试使事情变得更有效率。对于下面的代码,如果IP地址未更改为其他内容,例如,我还要发送电子邮件。我尝试使用不同的味精添加单独的body_text,并尝试创建另一个函数以在IP不变的情况下发送电子邮件。
任何有关如何解决此问题的想法都会有所帮助,因为我还有其他一些脚本想要做类似的事情。最终将添加oauth以提高安全性
from urllib.request import urlopen
import re
import smtplib
from_address = ''
to_address = ''
subject = 'IP'
username = ''
password = ''
url = 'http://checkip.dyndns.org'
print ("Our chosen IP address service is ", url)
request = urlopen(url).read().decode('utf-8')
ourIP = re.findall("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", request)
ourIP = str(ourIP)
print ("Our IP address is: ", ourIP)
def send_email(ourIP):
# Body of the email
body_text = ourIP + ' is my address'
msg = '\r\n'.join(['To: %s' % to_address, 'From: %s' % from_address, 'Subject: %s' %
subject, '', body_text])
# Send email!
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls() # Our security for transmission of credentials
server.login(username,password)
server.sendmail(from_address, to_address, msg)
server.quit()
print ("Email has been sent!")
# Open text file and extract contents
with open('last_ip.txt', 'rt') as last_ip:
last_ip = last_ip.read() # Read the text file
# Check to see if our IP address has really changed
if last_ip == ourIP:
print("Our IP address has not changed.")
else:
print ("We have a new IP address.")
with open('last_ip.txt', 'wt') as last_ip:
last_ip.write(ourIP)
print ("We have written the new IP address to the text file.")
send_email(ourIP)
答案 0 :(得分:0)
最终移动了周围的东西,并改用了它:
def send_email(ourIP,last_ip):
if last_ip == ourIP:
print("Our IP address has not changed.")
body_text = ourIP + ' is still the same'
else:
body_text = ourIP + ' is different'
print ("We have a new IP address.")
with open('last_ip.txt', 'wt') as last_ip:
last_ip.write(ourIP)
print ("We have written the new IP address to the text file.")