#coding:utf-8 import smtplib from email.mime.text import MIMEText from email.header import Header from email.utils import parseaddr, formataddr import requests import time cityname = ‘南宁‘ #key为聚合平台注册的api接口 key = ‘*******************‘ #发送邮件 sender = ‘2574******@qq.com‘ #接受邮件 receiver = ‘9801*****@qq.com‘ #pswd为发送邮件账号开启smtp服务获得的短匙,不是密码,需要去邮箱设置 pswd = ‘************‘ #通过聚合平台api获得天气预报 def get_weather(): url = ‘http://v.juhe.cn/weather/index?format=2&cityname={cityname}&key={key}‘ data = requests.get(url.format(cityname=cityname,key=key)).json() if data[‘resultcode‘] == ‘200‘: return "今天温度为{temp},{weather},{wind} \n{advice} \n明天的气温为{ttemp} ,{tweather}".format(temp=data[‘result‘][‘today‘][‘temperature‘], weather=data[‘result‘][‘today‘][‘weather‘], wind=data[‘result‘][‘today‘][‘wind‘], advice=data[‘result‘][‘today‘][‘dressing_advice‘], ttemp=data[‘result‘][‘future‘][1][‘temperature‘], tweather=data[‘result‘][‘future‘][1][‘weather‘]) else: return "对不起,没有找到该城市的天气数据。" #发送邮件 def send_email(str): message = MIMEText(str,‘plain‘,‘utf-8‘) message[‘From‘] = Header(‘每日推送‘,‘utf-8‘).encode() message[‘To‘] = Header(‘you‘,‘utf-8‘).encode() message[‘Subject‘] = Header(‘带给你每天不一样的问候‘,‘utf-8‘).encode() smtp_obj = smtplib.SMTP_SSL(‘smtp.qq.com‘,465) smtp_obj.login(sender,pswd) smtp_obj.sendmail(sender,[receiver],message.as_string()) smtp_obj.quit() str = get_weather() send_email(str)
期间遇到一些问题
1,邮箱设置,获得短匙,开始用的邮箱密码一直不对,需要开启以下两个服务
2,使用SMTP_SSL协议,服务器地址为smtp.qq.com
3,发送邮件成功后自动到接收邮件的垃圾箱,百度了下好像没什么解决办法,自己试了下,在垃圾箱中设置这不是垃圾邮件,以后发的邮件就都正常了。