예외 경우에 인쇄되는 오류 메시지를 사용자에게 이메일로 어떻게 보내나요? (How to send an error message being printed in an exception case by email to a user?)


문제 설명

예외 경우에 인쇄되는 오류 메시지를 사용자에게 이메일로 어떻게 보내나요? (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()

다음은 Python 셸에 표시되는 오류입니다.

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

'e' 변수에 인쇄되는 오류 메시지를 이메일로 다른 사람에게 보내는 방법

감사합니다


참조 솔루션

방법 1:

The logging module itself has smtp handler you can do something like this:

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')

for more info see doc

(by Gavya MehtaEternal)

참조 문서

  1. How to send an error message being printed in an exception case by email to a user? (CC BY‑SA 2.5/3.0/4.0)

#Python #python-logging #mime-mail






관련 질문

Python - 파일 이름에 특수 문자가 있는 파일의 이름을 바꿀 수 없습니다. (Python - Unable to rename a file with special characters in the file name)

구조화된 배열의 dtype을 변경하면 문자열 데이터가 0이 됩니다. (Changing dtype of structured array zeros out string data)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

for 루프를 중단하지 않고 if 문을 중지하고 다른 if에 영향을 줍니다. (Stop if statement without breaking for loop and affect other ifs)

기본 숫자를 10 ^ 9 이상으로 늘리면 코드가 작동하지 않습니다. (Code fails to work when i increase the base numbers to anything over 10 ^ 9)

사용자 지정 대화 상자 PyQT5를 닫고 데이터 가져오기 (Close and get data from a custom dialog PyQT5)

Enthought Canopy의 Python: csv 파일 조작 (Python in Enthought Canopy: manipulating csv files)

학생의 이름을 인쇄하려고 하는 것이 잘못된 것은 무엇입니까? (What is wrong with trying to print the name of the student?)

다단계 열 테이블에 부분합 열 추가 (Adding a subtotal column to a multilevel column table)

여러 함수의 변수를 다른 함수로 사용 (Use variables from multiple functions into another function)

리프 텐서의 값을 업데이트하는 적절한 방법은 무엇입니까(예: 경사하강법 업데이트 단계 중) (What's the proper way to update a leaf tensor's values (e.g. during the update step of gradient descent))

Boto3: 조직 단위의 AMI에 시작 권한을 추가하려고 하면 ParamValidationError가 발생합니다. (Boto3: trying to add launch permission to AMI for an organizational unit raises ParamValidationError)







코멘트