1. 程式人生 > >python編寫檢視是否有新郵件的小工具

python編寫檢視是否有新郵件的小工具

  最近因為總是要檢視是否有重要的工作郵件,頻繁登入幾個郵件網站,覺得很繁瑣,於是用python寫了個查詢是否有新郵件和下載郵件資訊的小工具。至於為什麼沒寫收取郵件的工具,是因為不是每天都收到新郵件,而且現在很多廣告郵件,不必都收取。

  使用過程:先通過小工具檢查是否有新郵件,如果有,就下載郵件資訊,檢視郵件標題,確認是有用的郵件,才登入郵件網站收取。

Ps:程式碼測試環境win7+python2.5.2

測試1:檢查是否有新郵件


測試2:下載郵件基本資訊


程式碼包:checkmail
getNewMailNum:檢視是否有新郵件
checkMail:下載郵件資訊(發信人,發信日期,標題)
InfoOutPut:輸出郵件資訊
  工作原理是使用了imaplib模組,經過測試,發現126,163,gmail,qq郵件支援imap協議,其餘sina,hotmail等還不支援,所以不是所有郵箱都可以使用。再次鄙視某些公司,口說為人民服務,實際暗懷私心,不積極開源與參與標準。哦,話題扯遠了。:-)
   實際寫起來不難,但是我對郵件資訊的下載,是把所有收件箱的郵件都下載,無法過濾出新郵件,這是因為對imaplib還未了解透徹,無法實現只下載新郵件的資訊,如果哪位讀者知道,可以告訴我,加以改進。
  還有一個問題花了點時間,也沒有解決,就是中英文混合字串輸出格式問題。因為中文佔2個英文字元寬度。中英文混合在一起輸出(我設定每行輸出76個英文字元寬度),就會無法對齊,網上查了一些資料,是由於作業系統對單箇中文和英文的畫素設定不同而且中文畫素寬不是英文的畫素寬度的兩倍造成的。所以,大家在收取含有大量中文的郵件就會格式無法對齊。
  另外,對於輸出中文的解決方案,我是先設定python的預設字元為gbk(因為發現有些郵件中文編碼是gbk,不是gb2312),否則print出來是亂碼。
import sys
reload(sys)
sys.setdefaultencoding('gbk')

然後對獲取的郵件字元解碼
email.Header.decode_header(msg["Subject"])
Header.decode_header會把字串解碼,告訴你這串字元的編碼是什麼,然後把字元統一轉成unicode,就可以列印輸出了。

my_unicode(s, encoding)

--------------------getNewMailNum-------------------------------------

#-*- encoding: utf-8 -*-
#author : rayment
#CreateDate : 2012-06-24
import imaplib
import re
import InfoOutPut

def gmail_checker(mailhost, username, password, flag = 0):


        i=imaplib.IMAP4_SSL(mailhost)
        try:
                i.login(username, password)
                x, y=i.status('INBOX', '(MESSAGES UNSEEN)')
                messages=int(re.search('MESSAGES\s+(\d+)', y[0]).group(1))
                unseen=int(re.search('UNSEEN\s+(\d+)', y[0]).group(1))
                #print "-------------------------------------------------"
                #print "%s : total %i messages, %i unseen." % (username, messages, unseen)
                outstr = []
                outstr.append(username)
                outstr.append(' : total ')
                outstr.append(str(messages))
                outstr.append(' messages, ')
                outstr.append(str(unseen))
                outstr.append(' unseen.')
                
                InfoOutPut.InfoOutPut(''.join(outstr), flag)
        finally:
                i.logout()

if __name__ == '__main__':
    gmail_checker('imap.163.com', 'accout', 'xxxxxx', 1)
    gmail_checker('imap.126.com', 'accout', 'xxxxxx')

--------------------checkMail---------------------------------------

#-*- encoding: utf-8 -*-
#author : rayment
#CreateDate : 2012-06-24
import imaplib
import email
import InfoOutPut

import sys
reload(sys)
sys.setdefaultencoding('gbk')


def my_unicode(s, encoding):
    if encoding:
        return unicode(s, encoding)
    else:
        return unicode(s)


def checkMail(mailhost, accout, password):
    con = imaplib.IMAP4_SSL(mailhost)
    con.login(accout, password)
    try:
        con.select('INBOX', readonly=True)
        flag, data = con.search(None, 'ALL')
        InfoOutPut.initOutPut()
        InfoOutPut.InfoOutPut('Accout : ' + accout)
        for num in (data[0]).split(' '):
            typ, msg_data = con.fetch(num, '(RFC822)')
            InfoOutPut.InfoOutPut('No : ' + num)
            for response_part in msg_data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])
                    ls = msg["From"].split(' ')
                    strfrom = ''
                    if(len(ls) == 2):
                        fromname = email.Header.decode_header((ls[0]).strip('\"'))
                        strfrom = 'From : ' + my_unicode(fromname[0][0], fromname[0][1]) + ls[1]
                        InfoOutPut.InfoOutPut(strfrom, 2)
                    else:
                        strfrom = 'From : ' + msg["From"]
                        InfoOutPut.InfoOutPut(strfrom, 2)
                    strdate = 'Date : ' + msg["Date"]
                    InfoOutPut.InfoOutPut(strdate, 2)
                    subject = email.Header.decode_header(msg["Subject"])
                    strsub = 'Subject : ' + my_unicode(subject[0][0], subject[0][1])
                    InfoOutPut.InfoOutPut(strsub)      
    finally:
        try:
            con.close()
        except:
            pass
        con.logout()

if __name__ == '__main__':
    checkMail('imap.126.com', 'accout', 'xxxx')
    #checkMail('imap.gmail.com', 'accout', 'xxxxx')

------------------------------------------------

完整程式碼包下載:http://download.csdn.net/detail/raymentblog/4394333