【问题标题】:Unable to send email when exception is raised via smtplib python通过 smtplib python 引发异常时无法发送电子邮件
【发布时间】: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


    【解决方案1】:

    您需要为开发者设置一个 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")
    
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2020-09-19
      • 2021-12-01
      • 1970-01-01
      • 2016-03-13
      相关资源
      最近更新 更多