Python exception handling and email notification
Python exception handling
use
try:
print('try...')
r = 10 / 0
print('result:%s' % r)
except ZeroDivisionError as e:
print('error happened:',e)
raise e
finally:
print('done')
print('ok')
Put the possible exceptions into try and do the corresponding processing.
Among them raise e
, the error is reported currently, detailed information will be written, and track to a specific line.
Send mail with 163 mailbox
It should be noted that the smtp service needs to be turned
on for the 163 mailbox. How to turn on the SMTP service for the 163 mailbox?
After opening, there will be a client authorization password, which is in the codeuser_passwd
import smtplib
from email import encoders
from email.utils import formatdate
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import *
user_name = "[email protected]"
user_passwd = "smtp_passwd"
smtp_server = "smtp.163.com"
subject = "Project error info"
def send_email(from_user, to_user_list, subject, body):
to_user = ",".join(to_user_list)
#email info
msg = MIMEText(body,'plain','utf-8')
# msg = MIMEMultipart('mixed')
msg['From'] = from_user
msg['To'] = to_user
msg['Subject'] = subject
msg['Date'] = formatdate(localtime = True)
#connect stmp and send email
smtp = smtplib.SMTP()
smtp.connect(smtp_server)
smtp.login(user_name, user_passwd)
smtp.sendmail(from_user, to_user, msg.as_string())
smtp.quit()
print('send over')
return
Catch exception and send email
try:
print('try...')
r = 10 / 0
print('result:%s' % r)
except ZeroDivisionError as e:
print('error happened:',e)
send_email(str(e))
raise e
finally:
print('done')
print('ok')