天天看点

python及时获得新邮件

#-*- encoding: utf-8 -*-
import sys
import locale
import poplib
from email import parser
import email
import string
import mysql.connector
import traceback
import datetime
from mysql.connector import errorcode
import time
import re

reload(sys);
sys.setdefaultencoding('utf8');

# 纭?瀹?杩?琛???澧???encoding
__g_codeset = sys.getdefaultencoding()
if "ascii"==__g_codeset:
    __g_codeset = 'utf8';
#

def object2double(obj):
    if(obj==None or obj==""):
        return 0
    else:
        return float(obj)
    #end if    
#

def getMailIndex():
    file = open('mailindex.txt',"r");
    lines = file.readlines();
    file.close();
    return int(lines[0]);
#    

def setMailIndex(index):
    f = open('mailindex.txt', 'w');
    f.write(index);
    f.close();
#    

def utf8_to_mbs(s):
    return s.decode("utf-8").encode(__g_codeset)
#

def utf8_to_gbk(s):
    return s.decode("utf-8").encode('gb2312')
#


def mbs_to_utf8(s):
    return s.decode(__g_codeset).encode("utf-8")
#

def gbk_to_utf8(s):
    return s.decode('gb2312').encode("utf-8")
#

def _queryQuick(cu,sql,tuple):
    try:
        cu.execute(sql,tuple);
        rows = []
        for row in cu:
            rows.append(row)
        #
        return rows
    except:
        print(traceback.format_exc())
    #end 
#
#?峰??淇℃??
def _queryRows(cu,sql):
    try:
        cu.execute(sql)
        rows = []
        for row in cu:
            rows.append(row)
        #
        return rows
    except:
        print(traceback.format_exc())
    #end 
#
#???????伴??浠?global hasNewMail;
hasNewMail=True;
#?ㄥ?宸茶?荤????浠舵?伴??
global globalMailReaded;
globalMailReaded=getMailIndex()+1;
#?峰???伴??浠?def getNewMail(conn2,cur2):
    try:
        global hasNewMail;
        global globalMailReaded;
        conn2.commit();
        rows=_queryRows(cur2,"select count(*) as message_count from hm_messages where messageaccountid=1");
        message_count=rows[0][0];
        if(hasNewMail):
            print('read mailindex.txt')
            globalMailReaded=getMailIndex()+1;
        #end if
        if(message_count<=globalMailReaded):
            hasNewMail=False;
            #print('Did not receive new mail,continue wait...')
            return None;#娌℃?伴??浠讹??存?ヨ???
        #end if 
        #?婚????绠?        host = '127.0.0.1'
        username = '[email?protected]'
        password = 'password'
        pop_conn = poplib.POP3(host)
        #print pop_conn.getwelcome()
        pop_conn.user(username);
        pop_conn.pass_(password);
        #Get messages from server:
        messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
        # Concat message pieces:
        messages = ["\n".join(mssg[1]) for mssg in messages]
        #Parse message intom an email object:
        messages = [parser.Parser().parsestr(mssg) for mssg in messages]
        print("get new mail!");
        print pop_conn.stat()
        print('%s readed mail count is %d,all mail count is: %d'%(datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"),globalMailReaded,len(messages)))
        message = messages[globalMailReaded];
        subject = message.get('subject')   
        h = email.Header.Header(subject)
        dh = email.Header.decode_header(h)
        #subject = unicode(dh[0][0], dh[0][1]).encode('utf8')
        #print >> f, "Date: ", message["Date"]
        #print >> f, "From: ", email.utils.parseaddr(message.get('from'))[1]
        #print >> f, "To: ", email.utils.parseaddr(message.get('to'))[1]
        #print >> f, "Subject: ", subject
        j = 0
        for part in message.walk():
            j = j + 1
            fileName = part.get_filename()
            contentType = part.get_content_type()
            mycode=part.get_content_charset();
            # 淇?瀛???浠?            if fileName:
                pass;
            elif contentType == 'text/plain':# or contentType == 'text/html':
                #淇?瀛?姝f??
                data = part.get_payload(decode=True)
                content=str(data);
                if mycode=='gb2312':
                    content= gbk_to_utf8(content)
                #end if    
                content=content.replace(u'\u200d','');
                setMailIndex(str(globalMailReaded));
                hasNewMail=True;
                pop_conn.quit();
                return (content,email.utils.parseaddr(message.get('from'))[1]);
            #end if
        #end for
    except:
        print("search hmailserver fail,try again");
        return None;
    finally:
        pass;
    #end try
#end def

#杩??ユ?版??搴?

conn2 = mysql.connector.connect(user='root', password='password',host='127.0.0.1',database='hmailserver',charset='gb2312');
cur2 = conn2.cursor();
#??瑕??跺?扮?靛????浠讹?灏辨??杩?涓?浜?浠惰?板??ㄤ?浠跺?涓?
#?板?ㄥ氨??寰????ヨ?㈤??绠憋?濡??????伴??浠跺氨璇诲??锛?骞舵?ヨ?㈠?抽??璇?搴?
while(True):
    mailtuple=getNewMail(conn2,cur2);
    if(mailtuple==None):
        #print('Did not search MySQL,continue loop...')
        time.sleep(0.5)
        continue;
    #end if
    (article,origin)=mailtuple;
#end while