python发邮件附件

 

python 2.7环境

复制代码
[root@localhost send_wrong_sql]# more send_fujin01.py 
#!/usr/bin/env python 
# -*- coding: UTF-8 -*- 

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import datetime
import time

mail_to = "aa@threegene.com"
mail_host = "mail.threegene.com:465"
mail_user = "yw@aa.com"
mail_pass = "123456"
mail_postfix = "aa.com"
receivers = ['aa@threegene.com', 'bb@threegene.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱


now_time = datetime.datetime.now()
yes_time = now_time + datetime.timedelta(days=-1)

def send_attach(file_name) :
        msg = MIMEMultipart()
        msg["Subject"] = "从库慢查询日志-"+str(now_time.strftime('%Y%m%d'))
        msg["From"] = mail_user  #邮件发送人
        msg["To"] = ','.join(receivers)
        part = MIMEText("123从库慢查询日志,请查看附件!",_charset="utf-8")
        msg.attach(part)
        part = MIMEApplication(open(file_name, 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename="slowquery_123_"+str(now_time.strftime('%Y%m%d'))+".log")
        msg.attach(part)

        try:
            s = smtplib.SMTP_SSL(mail_host)
            s.login(mail_user, mail_pass)
            s.sendmail(mail_user, receivers, msg.as_string())
            s.close()
        except Exception as e:
            print("error:", e)



def get_filecount(file_name) :
        count=-1
        for count, line in enumerate(open(file_name,'rU')):
                pass
        count+=1
        return count

if __name__ == '__main__' :
        file_name="/tmp/slowquery/daily_slow_query_"+str(yes_time.strftime('%Y_%m_%d'))+".log"
        file_row=get_filecount(file_name)
        print(file_row)
        if file_row > 0:
                send_attach(file_name)
复制代码

 

posted @   slnngk  阅读(42)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示