欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年08月10日 12:21:20   作者:liumengcheng  
這篇文章主要介紹了Python編程實(shí)現(xiàn)及時(shí)獲取新郵件的方法,涉及Python實(shí)時(shí)查詢郵箱及郵件獲取相關(guān)操作技巧,需要的朋友可以參考下

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

#-*- 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');
# 確定運(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();
#只要收到電子郵件,就把這個(gè)事件記錄在事件庫中
#現(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

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • python pickle存儲(chǔ)、讀取大數(shù)據(jù)量列表、字典數(shù)據(jù)的方法

    python pickle存儲(chǔ)、讀取大數(shù)據(jù)量列表、字典數(shù)據(jù)的方法

    pickle模塊實(shí)現(xiàn)了用于序列化和反序列化python對(duì)象結(jié)構(gòu)的二進(jìn)制協(xié)議。這篇文章主要介紹了python pickle存儲(chǔ)、讀取大數(shù)據(jù)量列表、字典的數(shù)據(jù),需要的朋友可以參考下
    2019-07-07
  • Python手機(jī)號(hào)碼歸屬地查詢代碼

    Python手機(jī)號(hào)碼歸屬地查詢代碼

    這篇文章主要介紹了Python手機(jī)號(hào)碼歸屬地查詢代碼的相關(guān)資料,需要的朋友可以參考下
    2016-05-05
  • Django python雪花算法實(shí)現(xiàn)方式

    Django python雪花算法實(shí)現(xiàn)方式

    在Django項(xiàng)目中添加自定義模塊或應(yīng)用來封裝雪花算法,步驟包括創(chuàng)建應(yīng)用,編寫算法實(shí)現(xiàn)代碼至utils.py文件,及配置settings.py,此方法可方便在項(xiàng)目中隨處調(diào)用雪花算法,適用于需要唯一ID生成的場景
    2024-09-09
  • python 裝飾器的使用與要點(diǎn)

    python 裝飾器的使用與要點(diǎn)

    python的裝飾器本質(zhì)上是一個(gè)Python函數(shù),它可以讓其他函數(shù)在不需要做任何代碼變動(dòng)的前提下增加額外功能;裝飾器的返回值也是一個(gè)函數(shù)對(duì)象。簡單的說裝飾器就是一個(gè)用來返回函數(shù)的函數(shù)
    2021-05-05
  • Python?tuple方法和string常量介紹

    Python?tuple方法和string常量介紹

    這篇文章主要介紹了Python?tuple方法和string常量,文章基于python的相關(guān)資料展開詳細(xì)內(nèi)容,對(duì)初學(xué)python的通知有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-05-05
  • Python程序打包成可執(zhí)行文件exe詳解流程

    Python程序打包成可執(zhí)行文件exe詳解流程

    你是否也有希望過寫一些自己所需要的工具程序來使用,可有不想或者沒時(shí)間精力學(xué)別的語言,本篇文章教你如何將用python語言寫的程序打包成可執(zhí)行的exe文件
    2021-11-11
  • Python基于time模塊求程序運(yùn)行時(shí)間的方法

    Python基于time模塊求程序運(yùn)行時(shí)間的方法

    這篇文章主要介紹了Python基于time模塊求程序運(yùn)行時(shí)間的方法,涉及Python time模塊的使用及數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下
    2017-09-09
  • python 使用matplotlib 實(shí)現(xiàn)從文件中讀取x,y坐標(biāo)的可視化方法

    python 使用matplotlib 實(shí)現(xiàn)從文件中讀取x,y坐標(biāo)的可視化方法

    今天小編就為大家分享一篇python 使用matplotlib 實(shí)現(xiàn)從文件中讀取x,y坐標(biāo)的可視化方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • Mac中Python 3環(huán)境下安裝scrapy的方法教程

    Mac中Python 3環(huán)境下安裝scrapy的方法教程

    作為一名python爬蟲愛好者,怎能不折騰下Scrapy?折騰了許久之后終于安裝到了mac中,所以下面這篇文章主要給大家介紹了關(guān)于Mac系統(tǒng)中Python 3環(huán)境下安裝scrapy的相關(guān)資料,文中將實(shí)現(xiàn)的步驟一步步介紹的非常詳細(xì),需要的朋友可以參考下。
    2017-10-10
  • Python matplotlib實(shí)現(xiàn)圖表主題變換示例詳解

    Python matplotlib實(shí)現(xiàn)圖表主題變換示例詳解

    在畫圖的時(shí)候如果出現(xiàn)與圖表的顏色沖突或者看不清坐標(biāo)軸的情況,這時(shí)候可以通過更換坐標(biāo)軸風(fēng)格來解決,本文將為大家詳細(xì)介紹如何利用matplotlib實(shí)現(xiàn)圖表的主題樣式變換,需要的可以參考一下
    2022-03-03

最新評(píng)論