通过 smtplib python 引发异常时无法发送电子邮件

Unable to send email when exception is raised via smtplib python

我希望创建一个脚本,在遇到错误时向我发送有关错误详细信息的电子邮件。 但是当我在 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)

您需要为 Developer 设置一个 Google 帐户。如果您不想更改发送的安全设置 mail.There 有两种方法可以与您的电子邮件服务器建立安全连接:

1.Start 从一开始就使用 SMTP_SSL() 保护的 SMTP 连接。 2.Start 一个不安全的 SMTP 连接,然后可以使用 .starttls()

加密

而且我看到你用过

with smtplib.SMTP('smtp.mailtrap.io', 2525) as server

只需在您的目录中添加您想要查找错误的脚本,我建议您这样做:

import smtplib, ssl
import sys
import filename #your script

def senderrormail(script, err, date, time, tb = 'none'):
    port = 465  
    smtp_server = "smtp.gmail.com"
    sender_email = "your_sending_email"
    receiver_email = "receiver_email"  
    password = "your password"

    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}"""}

    context = ssl.create_default_context()

try:
    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message)
except:
    print("Mail not sent!")


now = datetime.now()
date = now.strftime("%d/%m/%Y")
time = now.strftime("%H:%M:%S")



try:
    t = traceback.print_exc(limit=None, file=filename, chain = True)
    senderrormail(fiename, t, date, time)
    print(t)    

except Exception as e:
    print("mail not sent")

希望对您有所帮助!