公司需求:客服通过WEB想查询 某一时间他发送的邮件的 状态,如果是拒绝是什么原因导致的。



#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import threading
import MySQLdb
import datetime,time


###########################################################################################
def Gainid(log):
    #mail id re
    mailid = re.compile(r'\w{11}\:')
    list_id = []
    for line in log:
        m  = mailid.search(line)
        if m is not None:
            list_id.append(m.group().strip(':'))
        else:
            continue
    return list(set(list_id))

def HandleLog(log,mailid):
    tomail = ''
    fmail = ''
    status = 'other'
    sdict={'status\=sent':'ok',
'Sender address rejected':'Sender address rejected',
'Recipient address rejected':'Recipient address rejected',
'said\: 550 [Mm]ailbox':'Mailbox not found',
'said\: 550 Domain frequency limited':'Domainfrequenc limited',
'said\: 55[3-4]':'junk mail',
'[uU]ser not exist':'user not exist',
'said\: 550 User suspended':'User suspended',
'said\: 550 User not found':'User not found',
'Message rejected as spam by Content Filterin':'Message rejected as spam by Content Filterin',
'said\: 550 No such user':'user not exist',
'[Uu]ser unknown':'user unknown'}
    for line in log:
        m = re.search(mailid,line)
        if m is not None:
            mailre = re.compile(r'[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+')
            timere = re.compile(r'^\w+\s+\d+\s\d{2}\:\d{2}:\d{2}')
            nt = timere.search(line)
            mtime = nt.group()
            n = mailre.search(line)
            if n is not None:
                f = re.search(r'from\=',line)
                t = re.search(r'to\=',line)
                if f is not None:
                    fmail = n.group().strip('<')
                if t is not None:
                    tmail = n.group().strip('<')
                    for  key in sdict:
                        statre = re.search(key,line)
                        if statre is not None:
                            status = sdict [key]
                        else:
                            pass
                    print ("id: %s date :%s  |frdr: %s |  todr: %s | status: %s" % (mailid,mtime ,fmail,tmail,status))
                    ttime = fromttime(mtime)    
                    sql = "insert into mailtest values('%s','%s','%s','%s','%s')" % (mailid,ttime ,fmail,tmail,status)            
                    insertmail(sql)
#                    if tomail:
#                        tomail = tomail+"(%s|%s)" % (tmail,status)
#                    else:
#                        tomail = "(%s|%s)" % (tmail,status)
        else:
            continue
def fromttime(mtime):
    today = datetime.date.today()
    
    yer   =     today.strftime("%Y")      
    mtime =  yer + mtime
    ntime =  time.strptime(mtime,"%Y%b  %d %H:%M:%S")
    ttime =  time.strftime('%Y-%m-%d %H:%M:%S',ntime)
    return ttime
def insertmail(sql):
    try:
        conn=MySQLdb.connect(host='localhost',user='root',passwd='',port=3306,db='mailawst')
        cur = conn.cursor()
    cur.execute(sql)
        cur.close()
    conn.commit()
        conn.close()
    except MySQLdb.Error,e:
        print "Mysql Error %d: %s" % (e.args[0],e.args[1])
         
        
def main(logfile):
    #open file
    f = open(logfile,'r')
    log = f.readlines()
    f.close()

    #mail id 
    mailid = Gainid(log)
    #HandleLog
    for i in range(len(mailid)):
        HandleLog(log,mailid[i])        
#    HandleLog(log,'850DA916966')        


if __name__ == "__main__":
    today = datetime.date.today() 
    oneday = datetime.timedelta(days=1)
#    d1 = datetime.datetime.now()
#    d3 = d1 + datetime.timedelta(hours=10)
#    d3.ctime()   
    yesterday = today - oneday
    tommorrow = today + oneday
    #print yesterday 
    zhi = yesterday.strftime("%Y%m%d")
    logfile = "/data/maillog/mail.log.%s" % zhi
        #logfile = "/data/maillog/mail.log.20140516"
    main(logfile)

WEB 展现通过apahce+php:


curdate()-1 limit 5';
//mysql_query($sql);    
mysql_select_db($mysql_database,$conn);
$result=mysql_query($sql,$conn);
$resultq=mysql_query($query,$conn);
//mysql_close($conn);   
echo ""."邮件发送状态查询"."" ;
echo " ";
$acceptmail = trim($_POST['acceptmail']);
$st = $_POST['st'];
$et = $_POST['et'];
$query = 'select * from mailtest where sendtime >='.'\''.$st.'\''.' and Date(sendtime)<='.'\''.$et.'\''.' and toaddress='.'\''.$acceptmail.'\'';
$resultq=mysql_query($query,$conn);
//echo $query." ";
//echo $acceptmail.$st.$et;
//查询条件
echo "";
?>
" method="post">

接收者邮件地址:'name='acceptmail' style='width:180;' />
邮件发送时间段:' class='text' style='width:85px;'/>
-' name='et' class='text' style='width:85px;'/>
 
 


"; while($field = mysql_fetch_field($result)){//使用while输出表头         if ($field->name=="mailid")         {         echo " "."邮件ID"." ";  }         if ($field->name=="sendtime")         {         echo " "."发送时间"." ";  }         if ($field->name=="fromaddress")         {         echo " "."邮件发送者"." ";  }         if ($field->name=="toaddress")         {         echo " "."邮件接收者"." ";  }         if ($field->name=="status")         {         echo " "."邮件发送结果"." ";  }  } echo ""; if(isset($_POST['submit']) && $_POST['submit']) {   $flag = 0; //按查询条件输出结果         while($rows = mysql_fetch_row($resultq))         {//使用while遍历所有记录,并显示在表格的tr中                 echo "";                 for($i = 0; $i < count($rows); $i++)                 echo " ".$rows[$i]."";              $flag++;         }         echo "";         if ($flag == 0)         echo "没有找到合适的记录"; } else { //默认输出结果         while($rows = mysql_fetch_row($result)){         //使用while遍历所有记录,并显示在表格的tr中                   echo "";                 for($i = 0; $i < count($rows); $i++)                 echo " ".$rows[$i]."";         }         echo ""; } ?>

showdate.js 时间那个 通用的JS!! 附件有!!

最终效果图!!

python分析postfix邮件日志的状态_第1张图片