此处只是做个记录,有问题自行查询调试。
环境:python 3.5.2
#获取IP地址使用的包
import requests
from bs4 import BeautifulSoup
#发送邮件使用的包
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def get_outer_ip(url):
r = requests.get(url)
txt = r.text
ip = txt[txt.find("[") + 1: txt.find("]")]
ipcode = "公网IP为:" + ip
return ipcode
def get_real_url(url=r'http://www.ip138.com'):
r = requests.get(url)
txt = r.text
soup = BeautifulSoup(txt, "html.parser").iframe
return soup["src"]
def sendmail(ipcode):
smtphost = 'smtp.qq.com' # smtp服务器
port = 465 # smtp服务器端口
user = 'xxxxx@qq.com' # 邮箱账号
pwd = '开启smtp时会生成一个激活码' # 非邮箱密码用激活码
receiver = 'xxxxxx@qq.com' # 收件人
# 主题 和 内容
subject = '外网IP地址'
content = ipcode
msg = MIMEText(content, 'plain', 'utf-8')
msg['from'] = Header(user)
msg['to'] = Header(receiver)
msg['subject'] = Header(subject)
try:
smtpObj = smtplib.SMTP_SSL(smtphost, port) # SSL加密
smtpObj.login(user, pwd)
smtpObj.sendmail(user, receiver, msg.as_string())
except smtplib.SMTPException as err:
print(err)
if __name__ == '__main__':
sendmail(get_outer_ip(get_real_url()))