如何修改Python脚本实现公网IP变更时自动发送邮件?
实现公网IP变化时自动发送邮件的修改方案
嘿,这个需求很实用!要让脚本只在公网IP变化时发邮件,核心就是记录并对比上次的IP地址,只有当新IP和旧IP不一样的时候才触发邮件发送。下面是修改后的完整代码,我会给你拆解关键改动:
关键改动点
- 新增变量存储上次的IP地址,首次运行时初始化为
None - 每次循环先获取当前公网IP,再和上次记录的IP对比
- 仅当IP变化(或首次运行)时才执行邮件发送逻辑
- 优化异常处理,避免网络问题或邮件发送失败导致脚本崩溃
- 修正了睡眠时长(你原来的
720秒是12分钟,改成7200秒才是12小时)
修改后的完整代码
from json import loads from urllib.request import urlopen import time import smtplib from smtplib import SMTPException # 初始化上次记录的IP,首次运行时为None last_ip = None # 可选:从本地文件读取上次的IP(避免脚本重启后重复发送) def load_last_ip(): try: with open("ip_record.txt", "r") as f: return f.read().strip() except FileNotFoundError: return None def save_last_ip(ip): with open("ip_record.txt", "w") as f: f.write(ip) # 启动时加载本地记录的IP last_ip = load_last_ip() while True: current_ip = None try: # 获取当前公网IP data = loads(urlopen("http://httpbin.org/ip").read()) current_ip = data["origin"] print(f"The public IP is : {current_ip}") except Exception as e: print(f"Failed to get public IP: {str(e)}") time.sleep(3600) # 获取IP失败时,1小时后重试 continue # 检查IP是否发生变化(首次运行时last_ip为None,也会触发发送) if current_ip != last_ip: try: # 使用with语句自动管理SMTP连接,避免资源泄漏 with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server_ssl: server_ssl.ehlo() server_ssl.login("fromemail@gmail.com", "password") # 优化邮件内容,让主题和正文更清晰 msg = f"""From: Automated Python Script <fromemail@gmail.com> To: First Last <toemail@gmail.com> Subject: Your Public IP Has Updated: {current_ip} Hello, Your public IP address has changed to: {current_ip} Best regards, Automated Python Script """ server_ssl.sendmail("fromemail@gmail.com", "toemail@gmail.com", msg) print("Successfully sent email with updated IP!") # 更新上次记录的IP,并保存到本地文件(可选) last_ip = current_ip save_last_ip(current_ip) except SMTPException as e: print(f"Error sending email: {str(e)}") except Exception as e: print(f"Unexpected error occurred: {str(e)}") # 每12小时检查一次IP time.sleep(7200)
额外说明
- 本地IP记录(可选):如果不想脚本重启后就发送一次初始IP,可以启用代码里的
load_last_ip和save_last_ip函数,它会把IP存在本地的ip_record.txt文件里,脚本重启时自动读取,这样只有真正的IP变化才会触发邮件。 - Gmail注意事项:如果你用的是Gmail,记得开启“低安全性应用访问”或者使用应用专用密码(开启2FA时),否则可能会登录失败。
- 异常处理:新增了获取IP失败的捕获逻辑,避免网络波动导致脚本直接崩溃,失败后会1小时重试一次,更稳定。
内容的提问来源于stack exchange,提问作者user9064672
相关产品推荐
相关产品推荐

