前言:因为每次更新好日报程序都要把最新版本发给同事,所以萌生了做个程序自动合并文件——压缩文件——发送邮件——删除文件,其中压缩文件用了网上比较好用的轮子,删除文件夹和文件夹下的所有内容用了shutil.rmtree
import zipfile
import os
import shutil
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase #附件
from email.mime.text import MIMEText
from email import encoders #转码
from datetime import date
def getToday():
'''获得今天的日期,并把名字改成0901这样的格式'''
today = date.today()
date_today = today.strftime("%m%d")
return date_today
def combine_file():
'''首先判断是否有周末日报,如果有的话就删除;然后把日报和数据这两个文件夹复制到周末日报中'''
if os.path.exists(r'C:\Users\Administrator\Desktop\报表\周末日报'):
shutil.rmtree(r'C:\Users\Administrator\Desktop\报表\周末日报')
os.mkdir(r'C:\Users\Administrator\Desktop\报表\周末日报')
shutil.copytree(r'C:\Users\Administrator\Desktop\报表\日报',r'C:\Users\Administrator\Desktop\报表\周末日报\日报')
shutil.copytree(r'C:\Users\Administrator\Desktop\报表\数据',r'C:\Users\Administrator\Desktop\报表\周末日报\数据')
def zipDir(dirpath, outFullName):
'''
压缩指定文件夹
:param dirpath: 目标文件夹路径
:param outFullName: 压缩文件保存路径+XXXX.zip
:return: 无
'''
zip = zipfile.ZipFile(outFullName, 'w', zipfile.ZIP_DEFLATED)
for path, dirnames, filenames in os.walk(dirpath):
#去掉目标和路径,只对目标文件夹下边的文件及文件夹进行压缩(包括父文件夹本身)
this_path = os.path.abspath('.')
fpath = path.replace(this_path, '')
for filename in filenames:
zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.close()
def server_pre(msg):
'''邮件服务器基础设置'''
server = smtplib.SMTP('mail.sh.ctc.com')
server.starttls()
fromAddr = '**@shtel.com.cn' # 发件人
myPass = '******' # 发件人密码
server.login(fromAddr, myPass)
server.send_message(msg)
server.quit()
def send_listing():
'''发送邮件'''
global msg_list
msg_list = MIMEMultipart()
msg_list['From'] = '**@shtel.com.cn'
msg_list['To'] = '**@shtel.com.cn, **@shtel.com.cn'
# msg_list['To'] = '**@189.cn, **@qq.com'
msg_list['Subject'] = '周末日报' + getToday()
body = '周末日报'+ getToday()
msg_list.attach(MIMEText(body))
with open(r"C:\Users\Administrator\Desktop\报表\周末日报.zip",'rb') as f:
#这里附件的MIME和文件名,这里是xls类型
mime = MIMEBase('zip','zip',filename='周末日报.zip')
#加上必要的头信息
mime.add_header('Content-Disposition','attachment',filename=('gb2312', '', '周末日报.zip'))
mime.add_header('Content-ID','<0>')
mime.add_header('X-Attachment-Id','0')
#把附件的内容读进来
mime.set_payload(f.read())
#用Base64编码
encoders.encode_base64(mime)
msg_list.attach(mime)
server_pre(msg_list)
print(">>>发送邮件成功!")
if __name__ =='__main__':
combine_file()
print('>>>合并报表成功!')
dirpath = r'C:\Users\Administrator\Desktop\报表\周末日报'
outFullName = r'C:\Users\Administrator\Desktop\报表\周末日报.zip'
zipDir(dirpath, outFullName)
print('>>>压缩文件成功!')
send_listing()
os.remove(outFullName)
shutil.rmtree(r'C:\Users\Administrator\Desktop\报表\周末日报')
print('>>>删除文件成功!')