Python: 当程序异常时候自动发送邮件

最近在做项目的时候,因为程序需要放到服务器上,为了防止程序在运行过程中报错而不知道,写了个当有异常的时候自动发送邮件的功能。

公司用的是outlook,所以用了win32组件Dispatch来实现outlook发送邮件,但是发现偶尔会有报win32com.gen_py异常,需要删除文件夹:C:UsersxxAppDataLocalTempgen_py3.80062FFF-0000-0000-C000-000000000046x0x9x6

代码实现如下:

def send_expection_mail(ex):
    """
    当程序中遇到任何问题的时候发送邮件通知到xxx
    :param e:
    :return:
    """
    try:
        outlook = Dispatch("outlook.Application")  # 固定写法
        mail = outlook.CreateItem(0)
        mail.To = 'xxx'
        mail.Subject = 'Exception(AutoTool): please help to check'
        body = ex + '<br><br>' + str(traceback.format_exc())
        mail.BodyFormat = 2  # 2表示HTML format,可以调整格式
        mail.HTMLBody = body
        mail.Send()  # 发送
    except Exception as e:
        e_str = str(e)
        if 'win32com.gen_py.' in e_str:
            folder_name = e_str[e_str.index('_py.') + 4: e_str.index("' ")]
            python_ver = f'{sys.version_info.major}.{sys.version_info.minor}'
            login_user = getpass.getuser()
            path = rf'C:Users{login_user}AppDataLocalTempgen_py{python_ver}{folder_name}'
            shutil.rmtree(path)
            time.sleep(5)  # 暂停5s再继续执行
            send_expection_mail(ex)


if __name__ == '__main__':
    try:
        main_code_here
    except Exception as e:
        send_expection_mail(str(e))
原文地址:https://www.cnblogs.com/danvy/p/15325411.html