python - 引发异常时如何发送通知电子邮件?
问题描述
我有try except
块里面for loop
。如果发生错误,我想发送一封电子邮件说“错误”,如果没有,我需要发送一封电子邮件说“成功”。
代码示例:
for file in files:
try:
if file.endswith('.csv'):
# converting source variable to str because shutil has some bugs
shutil.move(str(source) + "/" + file, dest_fs01 / current_year_folder / current_year_month_folder)
break
except Exception as e:
error = str(e)
我试过这样的东西,但如果没有错误,变量error
将不存在
for file in files:
try:
if file.endswith('.csv'):
# converting source variable to str because shutil has some bugs
shutil.move(str(source) + "/" + file, dest_fs01 / current_year_folder / current_year_month_folder)
break
except Exception as e:
error = str(e)
if len(error) > 0:
# sending email notifying about error
message4 = """From: <from@email.com>
To: <to@email.com>
Subject: Error
""" + error
smtpObj.sendmail(sender, receivers, message4)
else:
# sending email notifying about successful completion
message3 = """From: <from@email.com>
To: <to@email.com>
Subject: Success
解决方案
推荐阅读
- visual-studio - 在 Visual Studio 2017 中保留对齐空间
- javascript - 无法访问量角器中隐藏的 .bin 文件夹以获取我的 npm.json 文件
- python - 如何从 yelp_academic_dataset_business.json 创建另一个 csv 文件,其中仅包含酒店、餐厅或两者的业务?
- java - 在一段时间内使用 Collections.max (java)
- php - 用户离开 Woocommerce 中的某个页面后清空购物车
- python-3.x - 从 CSV 编写器写入的文件中删除最后一行(和空白行)
- xpath - 从包含另一个组件的组件中获取 href
- python - 使用 lambda 和列表推导时的延迟评估
- angular - 找不到或无法读取要导入的 Angular CLI SCSS 文件
- powershell - 我运行 STIG,我希望能够为那些 about:config 条目运行一组命令以获得设置的返回