python 邮件发送天气
import requests
import json
import smtplib;
from email.mime.text import MIMEText
from smtplib import SMTP
from email.header import Header
def get_weather(url):
rb = requests.get(url)
data = json.loads(rb.text)
return data
def send_email(mess,tips):
sender = '1111111111111@qq.com'#发送者
receivers = '222222222222222@qq.com'#接收者
#发送文本
weather_text = mess['date'] + "\n" + mess['high'] + "\n" + mess['low'] +"\n" + mess['type'] + "\n" + tips
message = MIMEText(weather_text,'plain', 'utf_8')
message['From'] = Header('今日天气','utf-8')
message['To'] = Header('lrq','utf-8')
message['Subject'] = Header('今日所在城市天气','utf-8')
smtper = SMTP('smtp.qq.com')
smtper.login(sender, 'xuilrvorahmfebbd')#这里是授权码,而不是qq密码
smtper.sendmail(sender, receivers, message.as_string())
print('邮件发送完成!')
def main(city = '西安'):
url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
weather = get_weather(url)
today_weather = weather['data']['forecast'][0]
send_email(today_weather,weather['data']['ganmao'])
if __name__ == '__main__':
main()
授权码可以登录自己的qq邮箱,在设置–账户–POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 这里开启
weater_text这里还可以优化,封装成一个方法,或者转换成其他格式。等有时间再修改
如果想要每天发送,window系统可以在任务计划程序里面添加