自制 txt 项目流程执行日志并邮件报送

每日流程留档文本自动报送

import datetime
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import time
import  os,base64
# 写入操作用于留档
def writetxt(content):
    today =  time.strftime("%Y-%m-%d", time.localtime())
    now_time = time.strftime("%H:%M:%S", time.localtime())
    filepath = os.path.dirname(__file__)
    print(filepath)
    filename = today+'.txt'
    file = os.path.join(filepath,filename)
    fp = open(file, 'a',encoding='utf-8')
    fp.write(today+' '+now_time) 
    fp.write('\n')
    fp.write(content)    
    fp.write('\n')
    fp.close()
     

# 发送结果及留档文件到管理员
def send_email(project_name):
    '''
    project_name 对应工程名
    '''
    # smtp服务器(内网问题)
    smtpserver = '**.***.**.**'
    user = '***@***.com'  # 如果使用MailEnable做邮件服务器,那么可以在该软件中查看用户名 一般该软件用户名会去掉.com ,比如boss@qiku
    passwd = '****'  # 授权码
    # 接收方信息(管理员)
    receiver = "*****@163.com" # 测试
    # receiver = email_address
    
    # 发送带附件的邮件
    message = MIMEMultipart() 
    message["from"] = user
    message["to"] = receiver
    message["subject"] = f"RPA流程{project_name}执行日志报送"  # 邮件的标题
    # 邮件正文
    mail_context =f"RPA流程执行日志请查收附件"
    message.attach(MIMEText(mail_context, 'plain', 'utf-8'))
    
    # 打印当前代码所在目录
    filepath = os.path.dirname(__file__)
    file_arr = ifile.find_files(path=filepath,sub_dir=False,time_sort='Desc')
    today =  time.strftime("%Y-%m-%d", time.localtime())
    for file in file_arr:
        if '.txt' and today in file:
            file_name = file
    print(file_name)
    
    # 构造附件2,传送当前目录下的 a.xls 文件
    att2 = MIMEText(open(file_name, 'rb').read(), 'base64', 'utf-8')
    att2["Content-Type"] = 'application/octet-stream'
    # 这里的filename可以任意写,写什么名字,邮件中显示什么名字  

    # 乱码问题处理
    file = os.path.basename(file_name)
    print(file_name,file)
    filename= bytes('=?utf-8?b?', encoding="utf8") + base64.b64encode(file.encode('UTF-8')) + bytes( '?=', encoding="utf8")
    filename= (bytes.decode(filename))
    att2.add_header('Content-Disposition', 'attachment', filename=filename)
    

    message.attach(att2)

    # 目标计算机积极拒绝
    server = smtplib.SMTP(host=smtpserver, port=25)
    server.login(user, passwd)
    server.sendmail(from_addr=user, to_addrs=receiver, msg=message.as_string())
    server.quit()
    print("finish")
    time.sleep(1)
    # 删除日志文件
    os.remove(os.path.join(filepath,file))
    return True