您的位置:首页 > 编程语言 > Python开发

python定时利用QQ邮件发送天气预报的实例

2017-11-17 09:00 1406 查看

大致介绍

好久没有写博客了,正好今天有时间把前几天写的利用python定时发送QQ邮件记录一下

1、首先利用request库去请求数据,天气预报使用的是和风天气的API(www.heweather.com/douments/api/s6/weather-forecast)

2、利用python的jinja2模块写一个html模板,用于展示数据

3、python的email构建邮件,smtplib发送邮件

4、最后使用crontab定时执行python脚本

涉及的具体知识可以去看文档,本文主要就是解释代码的结构

和风天气API

API没什么好说的,利用requests库去请求数据,然后提取出数据,使用方法和风天气API说的很详尽了

HTML模板

利用jinja2在和脚本同级的目录写一个HTML模板

写好模板,我们就需要在脚本中引入他,并给他传递数据

email构建邮件,smtplib发送邮件

注意:

1、首先需要开启QQ邮箱的SMTP服务,一般端口是465

2、在构建邮件和发送邮件时都需要接受者的邮箱,但是他们需要的数据格式是不同的,在构建邮件时,接受者邮箱需要转换成一个string,而在发送邮件时,接受者邮箱必须是一个list

crontab定时发送邮件

我想对crontab说:

这个crontab真的是大坑,坑了我好久,坑的我不行不行的

既然你们诚心诚意的发问了,那我就大发慈悲的告诉你们是那些坑吧

1、在crontab中要写绝对路径,包括python3,查看python的安装位置:

2、如果脚本中涉及了中文,记得一定要写export LANG="****",如果不知道属性是什么:

然后 crontab -e写入类似下面的代码:

表示在每晚的22:00执行脚本,具体的crontab语法可以自行搜索

邮件:

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只用于显示,必须是一个string
msg['To'] = ','.join(to_address)
msg['From'] = from_name
try:
s = smtplib.SMTP_SSL(serverip, serverport)
s.login(username, password)
# 这里的to_address是真正需要发送的到的mail邮箱地址需要的是一个list
s.sendmail(from_address, to_address, msg.as_string())
print('%s----发送邮件成功' % 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': '************ ', #注册和风天气会给你一个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']
# 日出时间
new_obj['sr'] = data['sr']
# 日落时间
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']
# 风向
new_obj['wind_dir'] = data['wind_dir']
# 风力
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": '预报君',
"to": TO,
"serverip": "smtp.qq.com",
"serverport": "465",
"username": "2*******@qq.com",
"password": "**********" #QQ邮箱的SMTP授权码
}
title = "别走,我给你看个宝贝"
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定时利用QQ邮件发送天气预报的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息