很久沒有寫博客了,正好今天有時間把前幾天寫的利用python定時發送QQ郵件記錄一下html
一、首先利用request庫去請求數據,天氣預報使用的是和風天氣的API(www.heweather.com/douments/api/s6/weather-forecast)python
二、利用python的jinja2模塊寫一個html模板,用於展現數據json
三、python的email構建郵件,smtplib發送郵件api
四、最後使用crontab定時執行python腳本app
涉及的具體知識能夠去看文檔,本文主要就是解釋代碼的結構spa
API沒什麼好說的,利用requests庫去請求數據,而後提取出數據,使用方法和風天氣API說的很詳盡了
3d
利用jinja2在和腳本同級的目錄寫一個HTML模板code
寫好模板,咱們就須要在腳本中引入他,並給他傳遞數據server
注意:htm
一、首先須要開啓QQ郵箱的SMTP服務,通常端口是465
二、在構建郵件和發送郵件時都須要接受者的郵箱,可是他們須要的數據格式是不一樣的,在構建郵件時,接受者郵箱須要轉換成一個string,而在發送郵件時,接受者郵箱必須是一個list
我想對crontab說:
這個crontab真的是大坑,坑了我很久,坑的我不行不行的
既然大家誠心誠意的發問了,那我就大發慈悲的告訴大家是那些坑吧
一、在crontab中要寫絕對路徑,包括python3,查看python的安裝位置:
二、若是腳本中涉及了中文,記得必定要寫export LANG="****",若是不知道屬性是什麼:
而後 crontab -e寫入相似下面的代碼:
表示在每晚的22:00執行腳本,具體的crontab語法能夠自行搜索
郵件:
ok👌
源代碼:
1 #!/usr/local/bin/python3 2 # coding=utf-8 3 4 import requests 5 import json 6 import smtplib 7 import jinja2 8 import os.path as pth 9 import time 10 from email.mime.text import MIMEText 11 from email.header import Header 12 13 HEFEN_D = pth.abspath(pth.dirname(__file__)) 14 LOCATION = '北京' 15 ORIGINAL_URL = 'https://free-api.heweather.com/s6/weather/forecast?parameters' 16 TO = ['8*******@qq.com', '2********@qq.com'] 17 18 19 def sendEmail(content, title, from_name, from_address, to_address, serverport, serverip, username, password): 20 msg = MIMEText(content, _subtype='html',_charset='utf-8') 21 msg['Subject'] = Header(title, 'utf-8') 22 # 這裏的to_address只用於顯示,必須是一個string 23 msg['To'] = ','.join(to_address) 24 msg['From'] = from_name 25 try: 26 s = smtplib.SMTP_SSL(serverip, serverport) 27 s.login(username, password) 28 # 這裏的to_address是真正須要發送的到的mail郵箱地址須要的是一個list 29 s.sendmail(from_address, to_address, msg.as_string()) 30 print('%s----發送郵件成功' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) 31 except Exception as err: 32 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) 33 print(err) 34 35 def get_data(): 36 new_data = [] 37 parametres = { 38 'location': LOCATION, 39 'key': '************ ', #註冊和風天氣會給你一個KEY 40 'lang': 'zh', 41 'unit': 'm' 42 } 43 44 try: 45 response = requests.get(ORIGINAL_URL,params=parametres) 46 r = json.loads(json.dumps(response.text,ensure_ascii=False,indent=1)) 47 r = json.loads(response.text) 48 except Exception as err: 49 print(err) 50 51 weather_forecast = r['HeWeather6'][0]['daily_forecast'] 52 for data in weather_forecast: 53 new_obj = {} 54 # 日期 55 new_obj['date'] = data['date'] 56 # 日出時間 57 new_obj['sr'] = data['sr'] 58 # 日落時間 59 new_obj['ss'] = data['ss'] 60 # 最高溫度 61 new_obj['tmp_max'] = data['tmp_max'] 62 # 最低溫度 63 new_obj['tmp_min'] = data['tmp_min'] 64 # 白每天氣情況描述 65 new_obj['cond_txt_d'] = data['cond_txt_d'] 66 # 風向 67 new_obj['wind_dir'] = data['wind_dir'] 68 # 風力 69 new_obj['wind_sc'] = data['wind_sc'] 70 # 降水機率 71 new_obj['pop'] = data['pop'] 72 # 能見度 73 new_obj['vis'] = data['vis'] 74 75 new_data.append(new_obj) 76 return new_data 77 78 79 80 def render_mail(data): 81 env = jinja2.Environment( 82 loader = jinja2.FileSystemLoader(HEFEN_D) 83 ) 84 return env.get_template('hefentianqi.html').render({'data': data}) 85 86 def main(): 87 config = { 88 "from": "2********@qq.com", 89 "from_name": '預報君', 90 "to": TO, 91 "serverip": "smtp.qq.com", 92 "serverport": "465", 93 "username": "2*******@qq.com", 94 "password": "**********" #QQ郵箱的SMTP受權碼 95 } 96 97 title = "別走,我給你看個寶貝" 98 99 data = get_data() 100 body = render_mail(data) 101 sendEmail(body, title, config['from_name'], config['from'], config['to'], config['serverport'], config['serverip'], config['username'], config['password']) 102 103 104 main()