Python3邮件发送

1.利用聚合网站的接口,获取深圳的天气预报

登录https://www.juhe.cn/,申请天气api接口,然后利用python去调用api获取近5日天气数据,并命名为weather.py

# coding=utf-8
import requests


class Weather_get:
    def __init__(self, city, key):
        self.city = city
        self.key = key

    def request(self):
        url = "http://apis.juhe.cn/simpleWeather/query?city=%s&key=%s" % (self.city, self.key)
        try:
            response = requests.get(url, timeout=10)
            return response.json()
        except Exception as e:
            print('页面访问超时......', e)

    def get_data(self):
        data = self.request()
        if data['reason'] == '查询成功!':
            try:
                for weather in data['result']['future']:
                    data_weather = {'date': weather['date'], 'temperature':weather['temperature'], 'weather': weather['weather']}
                    yield data_weather
            except Exception as e:
                print(e)
        else:
            print(data['reason'])

 

2.发送天气数据到对应邮箱

# coding=utf-8
from Class.weather import Weather_get
import smtplib
from email.mime.text import MIMEText
import json


class SendWeather:
    def get_weather(self):
        city = '深圳'  # 输入自己的城市
        key = "写自己的key"  # 申请之后会得到一个key,
        datas = Weather_get(city, key).get_data()  # 天气数据,是一个生成器
        weathers = []
        for w in datas:
            # 得到一个列表,包含5个字典对象,[{'date': '2020-06-18', 'temperature': '27/32℃', 'weather': '多云'}。。。]
            weathers.append(w)
        return weathers

    def send_weather(self):
        content = self.weather_format()
        email_host = 'smtp.163.com'  # 邮箱地址
        email_user = 'lovepachong@163.com'  # 发送者账号
        email_pwd = 'xxxxxxxxx'  # 发送者的密码,163邮箱是一串随机码,并不是你的登录密码
        maillist = '545186061@qq.com,lovepachong@163.com'   # 收件人邮箱,多个账号的话,用逗号隔开
        sender = email_user
        msg = MIMEText(content)  # 邮件内容
        msg['Subject'] = '小阿黑深圳天气提醒'  # 邮件主题
        msg['From'] = sender  # 发送者账号
        msg['To'] = maillist  # 接收者账号列表
        try:
            smtp = smtplib.SMTP(email_host, port=25)  # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
            smtp.login(email_user, email_pwd)  # 发送者的邮箱账号,密码
            smtp.sendmail(sender, msg['To'].split(','), msg.as_string())  # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
            smtp.quit()  # 发送完毕后退出smtp
            print('email send success.')
        except smtplib.SMTPException as e:
            print('发送失败....', e)

    # 将天气数据进行处理,使保存的数据更加美观
    def weather_format(self):
        weathers = self.get_weather()
        w0 = json.dumps(weathers[0], ensure_ascii=False)  # json数据转为字符串,需要使用dumps转储
        w1 = json.dumps(weathers[1], ensure_ascii=False)
        w2 = json.dumps(weathers[2], ensure_ascii=False)
        w3 = json.dumps(weathers[3], ensure_ascii=False)
        w4 = json.dumps(weathers[4], ensure_ascii=False)
        content = '''%s\n%s\n%s\n%s\n%s\n''' % (w0, w1, w2, w3, w4)
        return content

if __name__ == '__main__':
    s = SendWeather()
    s.send_weather()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值