Python发送以整个文件夹的内容为附件的邮件的教程
由于我经常需要备份文件夹下的内容到邮件里面,每个打开邮件,上传文件,发送,太过麻烦,其实每次发送的文件都是放在固定置的,只是邮件标题不同而已,于是用python为自己写了个发送文件到邮箱的小工具,在任意目录下执行该脚本,并指定邮件标,就将指定文件夹下的文件发送到邮箱中备份起来。
#!/usr/bin/envpython #coding:utf-8 fromsmtplibimportSMTP,quotedata,CRLF,SMTPDataError fromemail.MIMEMultipartimportMIMEMultipart fromemail.MIMEBaseimportMIMEBase fromemail.MIMETextimportMIMEText fromemailimportEncoders fromsysimportstderr,stdout importos importsys classExtendedSMTP(SMTP): defdata(self,msg): self.putcmd("data") (code,repl)=self.getreply() ifself.debuglevel>0:print>>stderr,"data:",(code,repl) ifcode!=354: raiseSMTPDataError(code,repl) else: q=quotedata(msg) ifq[-2:]!=CRLF: q=q+CRLF q=q+"."+CRLF #beginmodifiedsendcode chunk_size=2048 bytes_sent=0 whilebytes_sent!=len(q): chunk=q[bytes_sent:bytes_sent+chunk_size] self.send(chunk) bytes_sent+=len(chunk) ifhasattr(self,"callback"): self.callback(bytes_sent,len(q)) #endmodifiedsendcode (code,msg)=self.getreply() ifself.debuglevel>0:print>>stderr,"data:",(code,msg) return(code,msg) defcallback(progress,total): percent=100.*progress/total stdout.write('\r') stdout.write("%sbytessentof%s[%2.0f%%]"%(progress,total,percent)) stdout.flush() ifpercent>=100:stdout.write('\n') defsendmail(subject): MAIL_FROM='mymail@qq.com' MAIL_TO=['mymail@qq.com'] BAK_DIR='/path/to/bak/folder' msg=MIMEMultipart() msg['From']=MAIL_FROM msg['Subject']=subject msg.attach(MIMEText('testsendattachment')) forfilenameinos.listdir(BAK_DIR): part=MIMEBase('application',"octet-stream") part.set_payload(open(os.path.join(BAK_DIR,filename),"rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition','attachment;filename="%s"'%os.path.basename(filename)) msg.attach(part) try: smtp=ExtendedSMTP() smtp.callback=callback smtp.connect('smtp.qq.com',25) smtp.login('mymail','mypwd') smtp.sendmail(MAIL_FROM,MAIL_TO,msg.as_string()) smtp.close() os.system('rm-f%s/*'%BAK_DIR) exceptException,e: printe if__name__=='__main__': iflen(sys.argv)==1: print'Pleasespecificasubject' print'Usage:send_files<MAIL_SUBJECT>' else: sendmail(sys.argv[1])
安装:
配置好收件人,发件人,smtp地址,用户名,密码及要发送文件所在的路径。
将文件保存为send_files,保存到/usr/bin下面。
然后设置文件权限为可执行:
$chmod+xsend_files
用法:
$send_files'邮件标题'
还带有进度条哦~~