發送動態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 = 'username@qq.com'  # 發件人郵箱
receivers = ['username@163.com']  # 接收人郵箱
 
# 公網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)
相關文章
相關標籤/搜索