Python 3.x 如果Python脚本引发异常,如何将消息发送到我的gmail
我尝试了logging.handlers,但失败了 我从网络上获取代码,并尝试过Python 3.x 如果Python脚本引发异常,如何将消息发送到我的gmail,python-3.x,logging,Python 3.x,Logging,我尝试了logging.handlers,但失败了 我从网络上获取代码,并尝试过 import logging import logging.handlers smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.gmail.com", 587), fromaddr="name@gmail.com",
import logging
import logging.handlers
smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.gmail.com", 587),
fromaddr="name@gmail.com",
toaddrs="name@gmail.com",
subject=u"AppName error!")
logger = logging.getLogger()
logger.addHandler(smtp_handler)
try:
data= Data
except Exception as e:
logger.exception('Unhandled Exception')
在我的代码中,我使用了变量数据,并为其分配了甚至未定义的数据,因此它引发异常。我想在我的gmail中获得异常错误。我怎样才能做到这一点。如果有任何答案,我们将不胜感激。我的方法是在机器上安装邮件服务器,并使用os.popen调用它,而不是弄清楚smtplib是如何工作的: 我从中得到了这个解决方案,我发现它非常有用,尽管在这一点上它有点过时了
def sendmail_email(msg):
sendmail_location = "/usr/sbin/sendmail"
sendmail = os.popen("{} -t".format(sendmail_location), 'w')
sendmail.write(msg)
status = sendmail.close()
print("Sent the following email with sendmail, status {}:".format(status))
print(msg)
...
except Exception as e:
import traceback
message = """To:your_address@domain.com
From:your_program@domain.com
Subject:An exception has occurred.
Hello Father,
An exception has occurred:
{}
Here is the stack trace for the exception:
{}
Thank you,
-The Machine""".format(e.message, traceback.format_exc())
sendmail_email(message)