首页 > 解决方案 > 引发异常时如何发送通知电子邮件?

问题描述

我有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
    

标签: pythonexceptiontry-catch

解决方案


推荐阅读