python定時(shí)利用QQ郵件發(fā)送天氣預(yù)報(bào)的實(shí)例
大致介紹
好久沒有寫博客了,正好今天有時(shí)間把前幾天寫的利用python定時(shí)發(fā)送QQ郵件記錄一下
1、首先利用request庫(kù)去請(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沒什么好說(shuō)的,利用requests庫(kù)去請(qǐng)求數(shù)據(jù),然后提取出數(shù)據(jù),使用方法和風(fēng)天氣API說(shuō)的很詳盡了

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說(shuō):

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

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

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

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

ok!
源代碼:
#!/usr/local/bin/python3
# coding=utf-8
import requests
import json
import smtplib
import jinja2
import os.path as pth
import time
from email.mime.text import MIMEText
from email.header import Header
HEFEN_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_data
def 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)碼
}
title = "別走,我給你看個(gè)寶貝"
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í)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python判斷端口是否打開的實(shí)現(xiàn)代碼
python判斷端口是否打開的代碼,有需要的朋友可以參考下2013-02-02
Python批量發(fā)送post請(qǐng)求的實(shí)現(xiàn)代碼
昨天學(xué)了一天的Python(我的生產(chǎn)語(yǔ)言是java,也可以寫一些shell腳本,算有一點(diǎn)點(diǎn)基礎(chǔ)),今天有一個(gè)應(yīng)用場(chǎng)景,就正好練手了2018-05-05
Python基礎(chǔ)學(xué)習(xí)之函數(shù)和代碼復(fù)用詳解
函數(shù)能提高應(yīng)用的模塊性,和代碼的重復(fù)利用率,下面這篇文章主要給大家介紹了關(guān)于Python基礎(chǔ)學(xué)習(xí)之函數(shù)和代碼復(fù)用的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
python實(shí)現(xiàn)多線程及線程間通信的簡(jiǎn)單方法
這篇文章主要為大家介紹了python實(shí)現(xiàn)多線程及線程間通信的簡(jiǎn)單方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
Python聊天室?guī)Ы缑鎸?shí)現(xiàn)的示例代碼(tkinter,Mysql,Treading,socket)
這篇文章主要介紹了Python聊天室?guī)Ы缑鎸?shí)現(xiàn)的示例代碼(tkinter,Mysql,Treading,socket),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Python3 虛擬開發(fā)環(huán)境搭建過(guò)程(圖文詳解)
這篇文章主要介紹了Python3 虛擬開發(fā)環(huán)境搭建過(guò)程,本文通過(guò)圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01
Django項(xiàng)目如何正確配置日志(logging)
本文將教你如何在Django項(xiàng)目中正確配置日志(logging),讓Django生成log日志文件,并在程序運(yùn)行發(fā)生error級(jí)別故障時(shí)通知管理員。2021-04-04

