python 版本: 3.8.10
用于外网查询SMB服务器ipv6 地址。服务器定时查询本机ipv6地址,如地址变动则用电邮发送新地址。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import ssl
import socket
import sys
hostname = socket.gethostname()
ipv6_list = [info[4][0] for info in socket.getaddrinfo(hostname, None, socket.AF_INET6)]
ipv6=ipv6_list[2]
print(ipv6)
with open("ipv6.txt", "r", encoding="utf-8") as file:
ip=file.read()
if ip.strip()==ipv6.strip():
print(ip)
sys.exit() #退出程序
with open("ipv6.txt", "w", encoding="utf-8") as file1:
file1.write(ipv6)
# 邮件配置信息
smtp_server = "smtp.189.cn" # 139 邮箱的 SMTP 服务器地址
port = 465 # SSL 加密端口
sender_email = "133078654XX@189.cn" # 发件人邮箱
password = "iM!8mA(2R%0jGXXX" # 邮箱授权码(不是普通登录密码)
receiver_email = "133078654XX@189.cn" # 收件人邮箱
# 邮件内容
subject = "ipv6地址"
body =ipv6
# 构建邮件
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
# 添加邮件正文
message.attach(MIMEText(body, "plain"))
# 发送邮件
try:
context = ssl.create_default_context() # 创建 SSL 上下文
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password) # 登录邮箱
server.sendmail(sender_email, receiver_email, message.as_string()) # 发送邮件
print("邮件发送成功!")
except Exception as e:
print(f"邮件发送失败:{e}")