Pythonの例外処理は、163の電子メール通知を同時に試行します

Pythonの例外処理

使用する

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

考えられる例外を試行に入れて、対応する処理を実行します。
その中raise eで、現在エラーが報告されており、詳細情報が書き込まれ、特定の行まで追跡されます。

163メールボックスでメールを送信


163メールボックスのsmtpサービスをオンする必要があることに注意してください。163メールボックスのSMTPサービスをオンにするにはどうすればよいですか?
開くと、コードにクライアント認証パスワードがあります。user_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

例外をキャッチしてメールを送信する

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

おすすめ

転載: blog.csdn.net/qq_32507417/article/details/107250473