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

2024-05-16 00:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望创建一个脚本,当遇到错误时,会向我发送一封有关错误详细信息的电子邮件。 但是,当我在except block中调用该方法时,我不会收到任何电子邮件。但是,如果我写的是正常的,那就是除了区块外,我收到了邮件。你能告诉我哪里做错了吗

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)

Tags: ioimportdatetimedateservertime错误script
1条回答
网友
1楼 · 发布于 2024-05-16 00:23:40

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

1.使用SMTP_SSL()启动一个从一开始就受保护的SMTP连接。 2.启动一个不安全的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")

希望这有帮助

相关问题 更多 >