首页 > 解决方案 > Python 发送电子邮件事件虽然没有例外

问题描述

我编写了一个在 Windows 任务调度程序上执行的自动化 python(3.x) 代码,并且我修改了代码以在脚本未执行或执行脚本时出现异常/错误时发送电子邮件通知我。我遇到了代码问题,即使执行代码时没有异常或错误,我也会收到一封电子邮件。该代码旨在仅在执行脚本时出现异常或错误时发送电子邮件。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import logging
import logging.handlers

mail_content = '''Hi,

This is a sample Email.

Thank You
'''

#The mail addresses and password
sender_address = <sender_address>
sender_pass = <password>
receiver_address = <'receiver_address1', 'receiver_address2']
message = MIMEMultipart()
message['From'] = sender_address
message['Subject'] = 'PROD ShipTime Script'   #The subject line
message['To'] = ", ".join(receiver_address)
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))

def run_script():
    url = "url_1"
    
    payload = {}
    headers = {
      'Authorization': 'authorization'
    }
    response = requests.request("GET", url, headers=headers, data = payload).json()

    resp = json.dumps(response, indent=2)
    response1 = json.loads(resp)


    for i in range(len(response1['Response'])):
        ---do some action ----
        --- do some Action ---
        try:
            ---Do an action---
        except KeyExistsError:
            --- If there is an exception then do another Action ---
    return


def send_email(e):
    #Create SMTP session for sending the mail
    session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
    session.ehlo()
    session.starttls() #enable security
    session.login(sender_address, sender_pass) #login with mail_id and password
    text = message.as_string()
    session.sendmail(sender_address, receiver_address, text)
    session.quit()


def main():
    try:
        run_script()
    except Exception as e:
        send_email(e)
        print(e)
        print("Email Sent Successfully")

标签: pythonpython-3.x

解决方案


推荐阅读