0

我正在使用 Python3.7 如果代码不起作用,我正在尝试通过电子邮件将异常条件中的错误发送给用户,以下是我的代码:

except Exception as e:
logging.basicConfig(filename='logfile.log',format='%(asctime)s %(message)s',filemode='w')

logger=logging.getLogger()

logger.setLevel(logging.ERROR)

logger.error(e)
print("ERROR MESSAGE",e)

MY_ADDRESS = '*****@gmail.com'
PASSWORD = '*******'
MY_ADDRESS1 = '****@gmail.com'

s = smtplib.SMTP(host='smtp.gmail.com', port=***)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
print("login")
msg = MIMEMultipart()       # create a message

msg['From']=MY_ADDRESS
msg['To']=MY_ADDRESS1
msg['Subject']="ERROR MESSAGE"

message="ERROR"
msg.attach.as_string(MIMEText(e))
print("ERROR MAILED")

s.send_message(msg)
s.quit()

我想在正在打印的变量“e”中发送错误消息

但我无法这样做以下是错误:

这是我要打印和邮寄的错误:

ERROR MESSAGE [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'

这是 python shell 上显示的错误:

Traceback (most recent call last):
  File "C:\Python37\Sopan.py", line 30, in <module>
    wb.save(workbook_name)
  File "C:\Python37\lib\site-packages\openpyxl\workbook\workbook.py", line 408, in save
    save_workbook(self, filename)
  File "C:\Python37\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
    archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
  File "C:\Python37\lib\zipfile.py", line 1207, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python37\Sopan.py", line 88, in <module>
    msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python37\Sopan.py", line 88, in <module>
    msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'

如何通过电子邮件将打印在变量“e”中的错误消息发送给某人

谢谢你

4

1 回答 1

2

日志记录模块本身具有 smtp 处理程序,您可以执行以下操作:

import logging
import logging.handlers

smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.example.com", 25),
                                            fromaddr="someone@something.com", 
                                            toaddrs="receiver@mail.com",
                                            subject=u"ERROR IN YOURAPP!")


logger = logging.getLogger()
logger.addHandler(smtp_handler)

try:
  raise Exception
except Exception as e:
  logger.exception('Unhandled Exception')

有关更多信息,请参阅文档

于 2020-02-10T07:37:48.010 回答