国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python編程實(shí)現(xiàn)及時獲取新郵件的方法示例

2020-02-16 02:02:54
字體:
供稿:網(wǎng)友

本文實(shí)例講述了Python編程實(shí)現(xiàn)及時獲取新郵件的方法。分享給大家供大家參考,具體如下:

#-*- encoding: utf-8 -*-import sysimport localeimport poplibfrom email import parserimport emailimport stringimport mysql.connectorimport tracebackimport datetimefrom mysql.connector import errorcodeimport timeimport rereload(sys);sys.setdefaultencoding('utf8');# 確定運(yùn)行環(huán)境的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;#全局已讀的郵件數(shù)量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 = 'username@myserver.net'    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':        #保存正文        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#連接數(shù)據(jù)庫conn2 = mysql.connector.connect(user='root', password='password',host='127.0.0.1',database='hmailserver',charset='gb2312');cur2 = conn2.cursor();#只要收到電子郵件,就把這個事件記錄在事件庫中#現(xiàn)在就是循環(huán)查詢郵箱,如果有新郵件就讀取,并查詢關(guān)鍵詞庫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            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 沈丘县| 明溪县| 通榆县| 嘉鱼县| 盐亭县| 高安市| 皋兰县| 永靖县| 鄂伦春自治旗| 莱州市| 江都市| 石门县| 大渡口区| 山东省| 高尔夫| 松潘县| 犍为县| 鄂伦春自治旗| 内江市| 天峻县| 廉江市| 朔州市| 双峰县| 马边| 福鼎市| 雷山县| 泰和县| 山东省| 大关县| 淄博市| 二连浩特市| 博客| 兴隆县| 文登市| 敖汉旗| 简阳市| 喜德县| 韶关市| 观塘区| 柳河县| 砚山县|