【发布时间】:2020-05-21 09:44:20
【问题描述】:
我希望创建一个脚本,当遇到错误时会向我发送一封有关错误详细信息的电子邮件。 但是当我在 except 块中调用该方法时,我没有收到任何电子邮件。但是,如果我正常写,除了块之外,我会收到邮件。你能告诉我我哪里做错了吗?
import smtplib
from datetime import datetime
import traceback
def senderrormail(script, err, date, time, tb = 'none'):
sender = "Aayush Lakkad <alakkad@smtp.mailtrap.io>"
receiver = "Aayush Lakkad <alakkad@smtp.mailtrap.io>"
message = f"""\
Subject: Hi Mailtrap
To: {receiver}
From: {sender}
This is an alert mail,\n your python script for {script}\n has run into an error {err} \n\n on date {date} \t time {time} with {tb}"""
try:
with smtplib.SMTP('smtp.mailtrap.io', 2525) as server:
server.login("xxxxxxx", "xxxxxxx")
server.sendmail(sender, receiver, message)
print('mail sent!')
except:
print('Mail not sent!')
now = datetime.now()
date = now.strftime("%d/%m/%Y")
time = now.strftime("%H:%M:%S")
try:
raise TypeError('ohh')
except Exception as e:
t = traceback.print_exc()
senderrormail('emailalert', e, date, time)
print(t)
【问题讨论】:
标签: python python-3.x exception smtplib