python">__author__ = 'Qing'
# -*- coding: utf8 -*-
import sys
import urllib2
import json
import smtplib
from email.mime.text import MIMEText
from email.header import Header
reload(sys)
sys.setdefaultencoding("utf8")
class check_PM():
def __init__(self,url,city,token="..."):
self.city=city
self.header = {"Content-Type":"application/json"}
self.token=token
self.url=url
def get(self):
url=self.url+"?city="+self.city+"&token="+self.token
request=urllib2.Request(url,headers=self.header)
response=json.loads(urllib2.urlopen(request).read())
PM_result=response[0][u'pm2_5']
return PM_result
def mail(self):
PM_result=self.get()
sender = '...'
receiver=['...']
subject = u'目前Pm2.5 数值为 %d,请珍爱生命,做好防护措施' %PM_result
smtpserver = 'smtp.126.com'
username = '...'
password = '...'
msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8’,单字节字符不需要
msg['Subject'] = Header(subject, 'utf-8')
smtp = smtplib.SMTP()
smtp.connect('smtp.126.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
def run(self):
PM_result=self.get()
if int(PM_result)>1:
self.mail()
else :
pass
if __name__=="__main__":
check_PM('http://www.pm25.in/api/querys/pm2_5.json','cityname').run()
标签:python