python获得IP地址并发送到邮箱+Linux
时间: 2024-10-25 20:02:53 浏览: 23
python实现自动获取IP并发送到邮箱
在Python中获取本地IP地址并将其发送到电子邮件通常需要几个步骤。首先,你需要安装`socket`库来处理网络通信,`smtplib`和`email`库用于邮件发送,以及可能的`ssl`库如果涉及到SMTPS。这里是一个简单的示例:
```python
import socket
import smtplib
from email.mime.text import MIMEText
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# 这里尝试连接Google DNS服务器,返回的IP就是本机IP
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
except Exception:
ip = '127.0.0.1' # 如果无法连接,则可能是localhost
finally:
s.close()
return ip
def send_email(ip):
sender_email = 'your_email@example.com'
receiver_email = 'recipient_email@example.com'
password = 'your_password'
msg = MIMEText(f'您的IP地址是:{ip}')
msg['Subject'] = 'IP Address Update'
msg['From'] = sender_email
msg['To'] = receiver_email
try:
smtp_server = 'smtp.example.com' # 根据实际情况替换为你的SMTP服务器
if smtp_server.startswith('smtps'):
server = smtplib.SMTP_SSL(smtp_server, 465) # 使用SSL/TLS
else:
server = smtplib.SMTP(smtp_server, 587) # 非加密模式通常使用此端口
server.login(sender_email, password)
server.send_message(msg)
print("Email sent successfully.")
except Exception as e:
print(f"Error sending email: {str(e)}")
# 获取IP
ip = get_ip_address()
# 发送邮件
send_email(ip)
阅读全文