发送动态IP到邮件

#  -*-coding:utf8 -*-
#!/usr/bin/python

import smtplib
from email.mime.text import MIMEText

# IP
import urllib2
import re

# 时间函数
import time

 
# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # SMTP服务器
mail_user = "username"  # 用户名
mail_pass = "password"  # 密码 
 
sender = '[email protected]'  # 发件人邮箱
receivers = ['[email protected]']  # 接收人邮箱
 
# 公网IP函数
def changeip( ):
    url = urllib2.urlopen("http://txt.go.sohu.com/ip/soip")
    text = url.read()
    ip = re.findall(r'\d+.\d+.\d+.\d+',text)    
    ip=ip[0]
    return ip 

# 邮件函数
def changeemail(ip ):
    content = ip
    title = '公网IP'  # 邮件主题
    message = MIMEText(content, 'plain', 'utf-8')  # 内容, 格式, 编码
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
        smtpObj.login(mail_user, mail_pass)  # 登录验证
        smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
        print '发送成功!'
    except smtplib.SMTPException as e:
        print(e)


i = 0
agoip = '11.1'  # 邮件主题
while i < 1 :    
    ip = changeip( );
    print ip;    
    print agoip;   
    if ip != agoip: changeemail(ip);
    agoip =  ip
    time.sleep(1200)

猜你喜欢

转载自www.cnblogs.com/pxuan/p/10622605.html