Python教程

python发送邮件代码+注释(带数据库,纯发送邮件看博主其他博客)

本文主要是介绍python发送邮件代码+注释(带数据库,纯发送邮件看博主其他博客),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

代码功能

利用python查询数据库,发送报警邮件的案例

案例演示

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import pymysql
from datetime import timedelta, date,datetime
# from impala.dbapi import connect  #操做hive表需要用的库

def mysqlconn():
    conn = pymysql.connect(host='xxx.xxx.xxx.xxx', user='xx', passwd='xxx', db='xx', port=3306, charset='utf8')
    return  conn
# def hiveconn():
#     conn = connect(host='10.33.188.136', port=10000, database='ods', auth_mechanism='PLAIN')
#     return  conn
def Query(conn,sqlString,values):
    cursor=conn.cursor()
    cursor.execute(sqlString,values)
    returnData=cursor.fetchall()
    cursor.close()
    # conn.close()
    return returnData
def Dml(conn,sqlString,values):
    cursor=conn.cursor()
    cursor.execute(sqlString,values)
    conn.commit()
    cursor.close()
def monitor_sql(conn,tb):
    sd = (date.today() + timedelta(days=-1)).strftime('%Y%m%d')
    sql = 'select count(*) from '+tb
    values = []
    rva = Query(conn, sql, values)
    return list(rva)
def monitor(conn,tb,str):
    result = monitor_sql(conn,tb)
    if list(result[0])[0]>0 or result ==None:
        ssl_mail(str)
def ssl_mail(hs):
    try:
        #第三方SMTP服务
        mail_host = "smtp.qq.com"
        mail_user = "邮箱地址"
        mail_pass = "SMTP协议授权码"

        sender = '邮箱地址'
        receivers1 = ''.join(mail_user)
        receivers = receivers1.split(',')
        message = MIMEMultipart()
        message['From'] = Header("linan", 'utf-8')
        message['To'] =  Header(hs, 'utf-8')
        subject = str(hs)
        message['Subject'] = Header(subject, 'utf-8')

        #邮件正文内容
        message.attach(MIMEText(str(hs), 'plain', 'utf-8'))
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers,message.as_string())
        smtpObj.quit()
        print (datetime.now().strftime('%Y-%m-%d %H:%M:%S') + u":sucess")
    except Exception as e:
        print (e)
if __name__ == "__main__":
    # hiveconn = hiveconn()
    mysqlconn = mysqlconn()
    monitor(mysqlconn,'table(表名)','hive data alarm')
    # monitor(mysqlconn, 'ods_laqslsdj_czsx_info','mysql data alarm')

演示结果

出现下图样式表示成功
在这里插入图片描述

这篇关于python发送邮件代码+注释(带数据库,纯发送邮件看博主其他博客)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!