如何通过电子邮件将异常情况下正在打印的错误消息发送给用户?

How to send an error message being printed in an exception case by email to a user?

我正在使用 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' 中的错误消息发送给某人

谢谢你

日志模块本身有 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')

有关详细信息,请参阅 doc