用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

python天气预报 发送邮件提醒(和风天气接口)

2022-11-30 作者: Python自学举报

[python]代码库

#!/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()


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...