大致介紹
好久沒有寫博客了,正好今天有時(shí)間把前幾天寫的利用python定時(shí)發(fā)送QQ郵件記錄一下
1、首先利用request庫去請(qǐng)求數(shù)據(jù),天氣預(yù)報(bào)使用的是和風(fēng)天氣的API(www.heweather.com/douments/api/s6/weather-forecast)
2、利用python的jinja2模塊寫一個(gè)html模板,用于展示數(shù)據(jù)
3、python的email構(gòu)建郵件,smtplib發(fā)送郵件
4、最后使用crontab定時(shí)執(zhí)行python腳本
涉及的具體知識(shí)可以去看文檔,本文主要就是解釋代碼的結(jié)構(gòu)
和風(fēng)天氣API
API沒什么好說的,利用requests庫去請(qǐng)求數(shù)據(jù),然后提取出數(shù)據(jù),使用方法和風(fēng)天氣API說的很詳盡了

HTML模板
利用jinja2在和腳本同級(jí)的目錄寫一個(gè)HTML模板

寫好模板,我們就需要在腳本中引入他,并給他傳遞數(shù)據(jù)

email構(gòu)建郵件,smtplib發(fā)送郵件
注意:
1、首先需要開啟QQ郵箱的SMTP服務(wù),一般端口是465
2、在構(gòu)建郵件和發(fā)送郵件時(shí)都需要接受者的郵箱,但是他們需要的數(shù)據(jù)格式是不同的,在構(gòu)建郵件時(shí),接受者郵箱需要轉(zhuǎn)換成一個(gè)string,而在發(fā)送郵件時(shí),接受者郵箱必須是一個(gè)list

crontab定時(shí)發(fā)送郵件
我想對(duì)crontab說:

這個(gè)crontab真的是大坑,坑了我好久,坑的我不行不行的
既然你們誠心誠意的發(fā)問了,那我就大發(fā)慈悲的告訴你們是那些坑吧
1、在crontab中要寫絕對(duì)路徑,包括python3,查看python的安裝位置:

2、如果腳本中涉及了中文,記得一定要寫export LANG="****",如果不知道屬性是什么:

然后 crontab -e寫入類似下面的代碼:

表示在每晚的22:00執(zhí)行腳本,具體的crontab語法可以自行搜索
郵件:

ok!
源代碼:
#!/usr/local/bin/python3# coding=utf-8import requestsimport jsonimport smtplibimport jinja2import os.path as pthimport timefrom email.mime.text import MIMETextfrom email.header import HeaderHEFEN_D = pth.abspath(pth.dirname(__file__))LOCATION = '北京'ORIGINAL_URL = 'https://free-api.heweather.com/s6/weather/forecast?parameters'TO = ['8*******@qq.com', '2********@qq.com']def sendEmail(content, title, from_name, from_address, to_address, serverport, serverip, username, password): msg = MIMEText(content, _subtype='html',_charset='utf-8') msg['Subject'] = Header(title, 'utf-8') # 這里的to_address只用于顯示,必須是一個(gè)string msg['To'] = ','.join(to_address) msg['From'] = from_name try: s = smtplib.SMTP_SSL(serverip, serverport) s.login(username, password) # 這里的to_address是真正需要發(fā)送的到的mail郵箱地址需要的是一個(gè)list s.sendmail(from_address, to_address, msg.as_string()) print('%s----發(fā)送郵件成功' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) except Exception as err: print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print(err)def get_data(): new_data = [] parametres = { 'location': LOCATION, 'key': '************ ', #注冊(cè)和風(fēng)天氣會(huì)給你一個(gè)KEY 'lang': 'zh', 'unit': 'm' } try: response = requests.get(ORIGINAL_URL,params=parametres) r = json.loads(json.dumps(response.text,ensure_ascii=False,indent=1)) r = json.loads(response.text) except Exception as err: print(err) weather_forecast = r['HeWeather6'][0]['daily_forecast'] for data in weather_forecast: new_obj = {} # 日期 new_obj['date'] = data['date'] # 日出時(shí)間 new_obj['sr'] = data['sr'] # 日落時(shí)間 new_obj['ss'] = data['ss'] # 最高溫度 new_obj['tmp_max'] = data['tmp_max'] # 最低溫度 new_obj['tmp_min'] = data['tmp_min'] # 白天天氣狀況描述 new_obj['cond_txt_d'] = data['cond_txt_d'] # 風(fēng)向 new_obj['wind_dir'] = data['wind_dir'] # 風(fēng)力 new_obj['wind_sc'] = data['wind_sc'] # 降水概率 new_obj['pop'] = data['pop'] # 能見度 new_obj['vis'] = data['vis'] new_data.append(new_obj) return new_datadef render_mail(data): env = jinja2.Environment( loader = jinja2.FileSystemLoader(HEFEN_D) ) return env.get_template('hefentianqi.html').render({'data': data})def main(): config = { "from": "2********@qq.com", "from_name": '預(yù)報(bào)君', "to": TO, "serverip": "smtp.qq.com", "serverport": "465", "username": "2*******@qq.com", "password": "**********" #QQ郵箱的SMTP授權(quán)碼 } data = get_data() body = render_mail(data) sendEmail(body, title, config['from_name'], config['from'], config['to'], config['serverport'], config['serverip'], config['username'], config['password'])main()以上這篇python定時(shí)利用QQ郵件發(fā)送天氣預(yù)報(bào)的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選