python - 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")
解决方案
推荐阅读
- c++ - 从二维整数数组中的文件读取
- typescript - Ionic4 的键盘问题
- spring-boot - 使用 feign 和 kubernetes 进行负载平衡
- amazon-web-services - Lambda arn:aws:lambda:us-east-1:xxxxxxxxx:function:nodejs-alexa-skill 的触发器设置无效。错误代码:SkillManifestError
- android - 如何自动接受android权限
- r - dplyr - 如何过滤具有更多(总和)销售额的前 n 个组?
- html - 占位符“搜索表单”从我的计算机上的 c: 位置运行 html 时显示,但在服务器上没有 html 的副本
- reactjs - 使用 .reduce 包装 React 导出
- php - laravel - 制作一个搜索表单并在同一页面中显示结果
- python - 使用 node2vec 创建嵌入