1
回答
用python做的基于邮件的文件收集系统
华为云4核8G,高性能云服务器,免费试用   
现在已经有学生代码(就是平时学生交作业用的,把作业交到指定邮箱,然后把文件自动提取出来存到本机上),现在是要求添加可以收集办公室文件的功能,开发环境是python2.7,跪求各位大神了!
#!/usr/bin/python
#encoding=UTF-8
import email
import sys,os
import string
import re,ConfigParser
import subprocess
import logging
import smtplib
from email.mime.text import MIMEText
from email.Header import Header
from email.MIMEMultipart import MIMEMultipart
import urllib

USER_DIR=os.path.expanduser("~")
ATTACHMENTS_DIR = USER_DIR+"/学生上交作业/"
CODES=('gbk','gb2312','utf8')
COURSE_NAME="邮箱不正确"

#-------------test_link--------------------------
SUCCESS_LINK =  "/etc/m2fconf/succ.html"
FAILD_LINK="/etc/m2fconf/fail.html"
#-----------test_link END-------------------------

#==========================================================#
#-------Feedback class-------------------------------------#
#.eg: feedback = Feedback(msg['from'],link)                #
#   : feedback.send()                                      #
#describe: send feedback email containing a html content   #
#==========================================================#
class Feedback():
    link =""
    to_list = []
    #fill these blanks before you use it
    mail_host = "202.203.132.242"
    mail_user = "wdanxna"
    mail_pass = "liaoyunaa"
    mail_postfix = "163.com"
    FailSub="作业上交失败"


    def __init__(self):
        self.me = self.mail_user+"<"+self.mail_user+"@"+self.mail_postfix+">"

    def mysendMail(self,BackSubject,BackTo,BackData):
        global USER_DIR
        global COURSE_NAME
        try:

            mutt_options="-e 'set content_type=\"text/html\"' -e 'set from=swfu_cs@cs2.swfu.edu.cn' -e 'set realname=\"[课程]%s\"' -e 'set use_from=yes' -e 'set charset=\"UTF-8\"'" % COURSE_NAME
            os.system("echo  '%s' |mutt %s  -s %s  '%s' " % (BackData,mutt_options,BackSubject,BackTo))
        except Exception ,e:
            # print str(e)
            #print "ssssssssssssss"
            wlog(2,e)

    def send(self,to,link):
        self.to_list.append(to)
        self.link = link
        #msg['Subject'] = Header(self.sub,'utf-8')
        #msg['From'] = self.me
        #msg['To'] = ";".join(self.to_list)

        urlItem = urllib.urlopen(self.link)
        html = urlItem.read()
        urlItem.close()

        #html_part = MIMEText(html,'html')
        #html_part.set_charset('')
        #msg.attach(html_part)
        self.mysendMail(self.FailSub,";".join(self.to_list),html)

    def sendplus(self,to,link,append):
        global COURSE_NAME
        self.to_list.append(to)
        self.link = link
        _str = "第"+append+"次作业上交成功 \<br/> 请不要回复此邮件。"
        urlItem = urllib.urlopen(link)
        part_1 = urlItem.read()
        urlItem.close()

        html_center = "<div><h1>"+_str+"</h1></div>"

        html = html_center + part_1
        try:
            self.mysendMail(_str,";".join(self.to_list),html)
        except:
            print 'no'



#====Feedback class END=================



def wlog(level,msg):
    logger=logging.getLogger()
    handler=logging.FileHandler("Log_test.txt")
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    logger.info(msg)

def getFloder(_torecv,_subject):
    #函数名:getFloder
    #根据邮件接收者的附加名称和主题,构造文件的保存路径
    #路径:/Maildir/附加名称(别名)/主题/
    global ATTACHMENTS_DIR
    global USER_DIR
    global COURSE_NAME
    try:
        child =""
        cf = ConfigParser.ConfigParser()
        cf.read(USER_DIR+"/.mail2folder.conf")
#        if not cf.has_section(hto):
#	    return "MAIL_ERR"
        save2dir=cf.get(_torecv, 'dir')
        #child = cf.get(_torecv,'child')
    except ConfigParser.Error:
        save2dir=_torecv
    _subject=_subject.encode('utf-8')
    
    COURSE_NAME=save2dir
    if(child == "yes"):
        ATTACHMENTS_DIR += save2dir+'/'
    else:
        ATTACHMENTS_DIR +=  save2dir +'/'+_subject+'/'

    wlog(1,ATTACHMENTS_DIR)
    if not os.path.exists(ATTACHMENTS_DIR):
        os.makedirs(ATTACHMENTS_DIR)
 #   return "SUCCESS"

def strQ2B(ustring):
    rstring=""
    for uchar in ustring:
        inside_code=ord(uchar)
        if inside_code == 0x3000:
            inside_code=0x0020
        else:
            inside_code-=0xfee0
            if inside_code<0x0020 or inside_code >0x7e:
                rstring+=uchar
                rstring += unichr(inside_code)
    return rstring

def decode2utf(_str):
    global CODES
    _re=_str
    try:
        mcode = _str.split('?')[1]
        _str=email.Header.decode_header(_str)
        _str = _str[0][0]
        _re=_str.decode(mcode)
        return _re
    except:
        return _re


def dumpAttachmentFormMail(mailMsg):
    global ATTACHMENTS_DIR
    global SUCCESS_LINK
    global FAILD_LINK
    global USER_DIR
    #获取文件的to的附加名,要就接收文件名必须带有附加名要有+
    global CODES
    hto= mailMsg['To']  #syk+network@cs2.swfc.edu.cn
    hfrom = mailMsg['from']
    #print hto
    try:
        p = re.compile(r'.*\+(.*?)@.*?$')
        hto=p.search(hto).group(1)#network

        #print hto
    except:
        #如果to没有解析成功,则退出程序
        sys.exit(53)
        #hto='Trash'

    try:

        cf = ConfigParser.ConfigParser()
        cf.read(USER_DIR+"/.mail2folder.conf")
#	print hto
#	print cf.has_section(hto)
        if not cf.has_section(hto):
#	    print "-------"	
            raise Mail_Error, "课程不存在"

        hsubject=mailMsg['subject']
        hsubject= decode2utf(hsubject)
        p = re.compile(r'^\D*(\d+?)\D*?$')
        hsubject=p.search(hsubject).group(1)
        if string.atoi(hsubject) > 32:
            raise Mail_Error,"主题格式不正确"

        wlog(1,hsubject)
#        print hsubject
    except:
        #send email and exit
#	print "xxxx"
        feedback = Feedback()
        feedback.send(hfrom,FAILD_LINK)
        sys.exit()
        exit()

   # print hto,hsubject
    getFloder(hto,hsubject)



    for par in mailMsg.walk():
        if not par.is_multipart():
            name = par.get_param("name")
            if name:
                fname=decode2utf(name)

                #对文件进行检查,如果已经存在,则对文件重命名
                ffname=checkFile(ATTACHMENTS_DIR,fname)
                #wlog(1,'fname:'+fname)
                #print ATTACHMENTS_DIR+fname
                #获取附件
                data = par.get_payload(decode=True)
                try:
                    wlog(1,"w:"+ffname)
                    wlog(1,"abcd")
                    ffname=ffname.encode('utf-8')
                    wlog(1,'fname:'+ffname)
                    f = open(ffname, 'wb')
                    f.write(data)
                    f.close()
                    wlog(4,"ssssssssssss")


                except Exception,info:
                    #提取附件如果出错,则退出程序
                    wlog(1,"err:"+sys.exc_info()[0])
                    sys.exit(91)

    append = hsubject
    feedback = Feedback()
    feedback.sendplus(mailMsg['from'],SUCCESS_LINK,append)
    wlog(4,mailMsg['from'])


def checkFile(_dir,_filename):
    #检查文件是否已经存在,如果已经存在,则重新命名
    pos=_filename.rfind('.')
    file_ext=_filename[pos:]
    file_pre=_filename[:pos]
    fname=file_pre+file_ext
    p = re.compile(r'.*\((\d*?)\).*?$')

    #ffname:fullFileName
    ffname=_dir+_filename
    ffname=ffname.encode('utf-8')
    if os.path.isfile(ffname):
        files = os.listdir(_dir)
        i=1
        maxFileCount=1
        for f in files:
            pos2=f.rfind('.')
            try:
                if f[:pos2].index(file_pre)==0:
                    fnum=p.search(f).group(1)
                    if maxFileCount<string.atoi(fnum):
                            maxFileCount=string.atoi(fnum)
            except AttributeError:
                continue
            except ValueError:
                continue
        ffname=_dir+file_pre+'('+str(maxFileCount+1)+')'+file_ext
    return ffname


def openMailFile():

#    if len(sys.argv)!=2:
#        print "I need the name of the mail to purge!"
#        sys.exit(1)

    #open the file
    try:
        p = subprocess.Popen('cat',shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        lines = ''
        for line in p.stdout.readlines():
            lines+=line
        #ft=open(sys.argv[1],"r")
        #lines=ft.read()
        msg = email.message_from_string(lines)
        dumpAttachmentFormMail(msg)
    except IOError:
        print "no file!"
        sys.exit(1)



if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('utf-8')
    openMailFile()




举报
庞小海
发帖于4年前 1回/423阅
顶部