实习工作中的一个小任务,执行数据库中的sql语句,如果报错,将错误信息通过邮件的形式发送给数据库管理人员。
‘’‘
邮件发送模块
’‘’
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
class Send_email(object):
def __init__(self, my_subjects, my_contents):
# 设置建立通信的服务器信息
self.email_host = 'stmp.163.com'
# 设置登录邮箱的用户名和密匙
self.email_user = '用户名'
self.email_pass = 'xxxx' # 密钥,密钥的获取可以百度
# 发送邮件的邮箱账户
self.sender = 'xxxxx@163.com' # 邮箱账号
# 接收邮件的邮箱账户
self.receivers = ['xxx@qq.com'] # 接收用户列表,可以为1到多个
self.my_subjects = my_subjects # 邮件的主题
self.my_contents = my_contents # 邮件内容
def handle(self):
# 创建邮件对象
# 创建一个MIMEMultipart对象,这个对象就相当于一封邮件
message = MIMEMultipart()
# 设置发送方
message['From'] = self.sender
# 设置接收方
message['To'] = ';'.join(self.receivers)
# 设置邮件主题,也就是大标题,它是一个字符串
message['Subject'] = self.my_subjects
# 邮件正文设置
# 文本形式
content = self.my_contents
part1 = MIMEText(content, 'plain', 'utf-8')
# HTML格式
# 因为HTML格式一般比较长,因此我们用读取文件的方法
# with open('goldsunC.html', 'r') as f:
# content = f.read()
# part1 = MIMEText(content, 'html', 'utf-8')
# 将准备好的东西放在容器内
message.attach(part1)
# 发送邮件
# 与服务器建立通信并发送邮件
try:
receivers = self.receivers + [self.sender]
email_stmp = smtplib.SMTP()
email_stmp.connect('smtp.163.com', 25) # 请求连接服务器
email_stmp.login(self.email_user, self.email_pass) # 登录
email_stmp.sendmail(self.sender, receivers, message.as_string()) # 发送!
print('success')
except smtplib.SMTPException as e:
print('error', e)
if __name__ == '__main__':
send_email = Send_email('异常', '异常处理练习!')
send_email.handle()
下面是从数据库中获取sql语句,并执行,如果报错则发送邮件
from pymysql import *
import re
from send_email import Send_email
conn1 = connect(host='192.168.1.146', port=3306, user='user', password='pwd', database='Database', charset='utf8')
cursor1 = conn1.cursor()
sql1 = 'select * from CJZQ_QINGXI_SQL'
cursor1.execute(sql1)
results = cursor1.fetchall()
fields = results[0][3:6]
for field in fields:
if field:
text = re.findall(r'^.*\n', field)
try:
cursor1.execute(field)
conn1.commit()
except Exception as e:
print(e)
my_emails = Send_email('异常', str(e))
my_emails.handle()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)