200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > 用python实现自动化办公------定时发送邮件

用python实现自动化办公------定时发送邮件

时间:2020-03-30 09:57:20

相关推荐

用python实现自动化办公------定时发送邮件

用python实现自动化办公------定时发送邮件

摘要一、注册“和风天气”二、用python获取和风天气响应的json数据三、发送邮件四、写入日志程序源码

摘要

本文程序的主要功能:

定时将3日内的天气预报发送给指定邮箱发送方式选择,可以是群发,也可以是单发天气预报的城市自助选择异常处理机制日志写入

程序所用到的模块

smtplibrequestsjsonemailtimesys

所用模块的安装:

以上所用模块都可通过pip进行安装

安装命令:pip install moudle_name

阅读说明:

如果你想要每天早上起床电脑会自动给你的女朋友的邮箱发送未来几天的天气预报、温暖祝福、笑话、温馨可爱的图片等,那么我相信,你和你女朋友的感情会越来越深。如果没有女朋友也不用担心哦,跟着我一起学习自动化办公,你也一定能找到女朋友的!!!

今天的内容就是宅男们的福利呀,有了这个程序,从此,女神变女友,单车变摩托!

读者朋友们,用python实现自动化办公------定时发送邮件篇幅过长,请耐心阅读,对于出现的问题或者存在的疑问,可以加本人VX :cuiliang1666457052 进行交流。本程序代码不用做任何修改就可以正常使用,对于配置文件(一个关于城市ID的csv文件),可以私聊我,我将无偿发送。

本程序实现的功能定时发送QQ邮件需要进行QQ邮箱的STMP认证服务。我将具体操作步骤展示给大家。

关于用python实现自动化办公------定时发送邮件的GUI版本会增加协程设计,能够满足多并发功能,我会在近期发布,到时候读者朋友们可以免费下载哦!

准备工作:

第一步:打开QQ邮箱官网,登陆之后,在首页顶部点击"设置"

第二步:点击账户

第三步:开启SMTP服务

第四步:获取授权码

完成第三步之后,系统会让认证账户,而后会获得一个授权码,授权码是用来实现自动发送邮件的一个凭证,所以务必保管好授权码。

接收邮件服务器:,使用SSL,端口号993

发送邮件服务器:,使用SSL,端口号465或587

一、注册“和风天气”

注册和风天气官网,我们注册成功后,目的是得到一个key,从而连接和风天气的API,得到想要的的天气信息。

登陆之后,找到和风天气API文档,根据该文档流程建立属于自己的key,而后一定要记得这个key,在后续代码中需要用到这个key。

对于天气预报的种类,和风天气列出了很多种,在此我们选择“逐天天气预报”,三天开发版本,请求URL为/v7/weather/3d?,一定要记住这个URL。

对于请求参数,我们可以参照官网给出的要求,建立以下代码

parametres_tianqi = {'location': ID,#ID为城市的经度纬度坐标'key': 'xxxxxxxxxxxxxxxxxxxxx',#此处的key就是你在和风天气注册得到的key'lang': 'zh','unit': 'm'}

利用python的requests库,可以得到返回数据,官网API文档中给出的返回数据阳历如下图所示。

对于返回数据的参数描述如下所示。

二、用python获取和风天气响应的json数据

def recevie_weather_data(WEATHERORIGINAL_URL,ID):parametres_tianqi = {'location': ID,'key': 'xxxxxxxxxxxxxxxxxxxxxxxx','lang': 'zh','unit': 'm'}try:response = requests.get(WEATHERORIGINAL_URL,params=parametres_tianqi)r=json.loads(response.text)except Exception as err:print(err)finally:weather_forecast=r["daily"]print("获取天气数据成功!")print('_'*80)return weather_forecast

三、发送邮件

#发送邮件def send_mail_msg(msg_from,stm_passwd,msg_tos,subject,content):for msg_to in msg_tos:print(f'正在向{msg_to}发送邮件')msg = MIMEText(content)msg['Subject'] = subjectmsg['From'] = msg_frommsg['To'] = msg_totry:s = smtplib.SMTP_SSL("", 465)# 邮件服务器及端口号465或者587s.login(msg_from, stm_passwd)s.sendmail(msg_from, msg_to, msg.as_string())except:print("您的网络断开!!!发送失败")finally:print(msg_to, "发送成功")s_time=time.strftime("%Y-%m-%d %H:%M:%S")print("发送时间 ", s_time)save_send_records(msg_from,msg_to,subject,send_time=s_time)print('_' * 80)

四、写入日志

def save_send_records(sender,to,obj,send_time):with open(f'log_{sender}.csv','a+',encoding='utf-8') as f:f.write(send_time+','+to+','+obj+'\n')print(f"{sender} 日志保存成功!")

程序源码

import smtplibimport requestsimport jsonfrom email.mime.text import MIMETextimport timeimport sysCITY_ID='''_________________________________________CITY ID CITY ID北京101010100上海 10100重庆101040100无锡 101041800西安101050311江源 101060907_________________________________________'''#城市ID /qwd/LocationList/blob/master/China-City-List-latest.csv#保存日志def save_send_records(sender,to,obj,send_time):with open(f'log_{sender}.csv','a+',encoding='utf-8') as f:f.write(send_time+','+to+','+obj+'\n')print(f"{sender} 日志保存成功!")#获取天气def recevie_weather_data(WEATHERORIGINAL_URL,ID):parametres_tianqi = {'location': ID,'key': 'xxxxxxxxxxx','lang': 'zh','unit': 'm'}try:response = requests.get(WEATHERORIGINAL_URL,params=parametres_tianqi)r=json.loads(response.text)except Exception as err:print(err)finally:weather_forecast=r["daily"]print("获取天气数据成功!")print('_'*80)return weather_forecast#发送邮件def send_mail_msg(msg_from,stm_passwd,msg_tos,subject,content):for msg_to in msg_tos:print(f'正在向{msg_to}发送邮件')msg = MIMEText(content)msg['Subject'] = subjectmsg['From'] = msg_frommsg['To'] = msg_totry:s = smtplib.SMTP_SSL("", 465)# 邮件服务器及端口号465或者587s.login(msg_from, stm_passwd)s.sendmail(msg_from, msg_to, msg.as_string())except:print("您的网络断开!!!发送失败")finally:print(msg_to, "发送成功")s_time=time.strftime("%Y-%m-%d %H:%M:%S")print("发送时间 ", s_time)save_send_records(msg_from,msg_to,subject,send_time=s_time)print('_' * 80)send_format='''********************************************************日期 {},日出时间 {},日落时间 {},月升时间 {},月落时间 {}。月型 {},最高温度 {}°C,最低温度 {}°C,天气 {},风向 {}方向,风力 {}级。风速 {}km/h,降水量 {}毫米,紫外线强度 {},相对湿度 {}%,能见度 {}米,云量 {}%。********************************************************'''if __name__ == '__main__':id = '101010100'city_name="北京"print('_' * 80)print("在使用本程序前请确认城市ID,默认ID为北京(101010100)")print("其他城市ID请前往/qwd/LocationList/blob/master/China-City-List-latest.csv")print("或者在本文配置文件中查找")print('_' * 80)print(CITY_ID)id_flag=input("本程序适用于群发邮件,城市地址默认为北京,如需更改,请输入Y,其他键为默认:").strip()if id_flag=='Y':c_name=input("请输入城市名:").strip()city_id=''with open('./LocationList-master/China-City-List-latest.csv', 'r', encoding='utf-8')as f:datas = f.readlines()for data in datas:city = data.split(',')if city[2] == c_name:city_id = city[0]if city_id != '':print(f"您所查询的城市 {c_name} 已经找到,ID为 {city_id} ,系统将设置您选择的城市名为 {c_name} ")id=city_idcity_name=c_nameelse:print(f"您所查询的城市 {c_name} 未找到,系统还会默认为北京")msg_from = input("请输入发送方邮箱:").strip() # 发送方邮箱stm_passwd =input("请输入授权码:").strip() # 填入发送方邮箱的授权码msg_tos=[]while True:msg_to = input("请输入收件人邮箱(退出请输入Q):").strip() # 收件人邮箱if msg_to == 'Q':breakelse:msg_tos.append(msg_to)print('_'*80)print(msg_tos)print('_' * 80)flag=input("以上是您要发送的邮箱名单,城市名为 {},城市ID为 {} ,按N退出,任意键确认发送:".format(city_name,id)).strip()if flag=='N':print("安全退出中!......")time.sleep(3)sys.exit()print('_' * 80)subject = "穆穆Max的测试"# content = input("请输入正文").strip() # 正文print("获取天气信息中......")new_data=recevie_weather_data('/v7/weather/3d',ID=id)print(f"现在是北京时间 ",time.strftime("%Y-%m-%d %H:%M:%S"))begin_send_time = input("请输入发送的时间(格式14:00:00,默认为今天):").strip()print("时间检索中......")while True:if time.strftime("%H:%M:%S")==begin_send_time:print("正在按照预定时间发送消息")start_time=time.time()forecast_format_today = send_format.format(new_data[0]["fxDate"],new_data[0]["sunrise"],new_data[0]["sunset"],new_data[0]["moonrise"],new_data[0]["moonset"],new_data[0]["moonPhase"],new_data[0]["tempMax"],new_data[0]["tempMin"],new_data[0]["textDay"],new_data[0]["windDirDay"],new_data[0]["windScaleDay"],new_data[0]["windSpeedDay"],new_data[0]["precip"],new_data[0]["uvIndex"],new_data[0]["humidity"],new_data[0]["vis"],new_data[0]["cloud"])forecast_format_tomorrow = send_format.format(new_data[1]["fxDate"], new_data[1]["sunrise"],new_data[1]["sunset"], new_data[1]["moonrise"],new_data[1]["moonset"], new_data[1]["moonPhase"],new_data[1]["tempMax"], new_data[1]["tempMin"],new_data[1]["textDay"], new_data[1]["windDirDay"],new_data[1]["windScaleDay"], new_data[1]["windSpeedDay"],new_data[1]["precip"], new_data[1]["uvIndex"],new_data[1]["humidity"], new_data[1]["vis"],new_data[1]["cloud"])forecast_format_after_tomorrow = send_format.format(new_data[2]["fxDate"], new_data[2]["sunrise"],new_data[2]["sunset"], new_data[2]["moonrise"],new_data[2]["moonset"], new_data[2]["moonPhase"],new_data[2]["tempMax"], new_data[2]["tempMin"],new_data[2]["textDay"], new_data[2]["windDirDay"],new_data[2]["windScaleDay"], new_data[2]["windSpeedDay"],new_data[2]["precip"], new_data[2]["uvIndex"],new_data[2]["humidity"], new_data[2]["vis"],new_data[2]["cloud"])content=f'美好的一天就要开始,xx为亲爱的宝贝送上 {city_name} 三日内的天气预报'content+=forecast_format_today+forecast_format_tomorrow+forecast_format_after_tomorrowsend_mail_msg(msg_from,stm_passwd,msg_tos,subject,content)print("消息已经全部发送")stop_time=time.time()print("共花时 {} 秒".format(stop_time-start_time))print('正在安全退出')time.sleep(3)print("已经安全退出")print('_' * 80)sys.exit()

运行结果截图:

日志文件:

收到的邮件:

如果对我的文章感兴趣,请为我点一个赞,如果有python的知识需要了解或探讨,可以加本人微信cuiliang1666457052

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。