利用Python imaplib和email模組 讀取郵件常值內容及附件內容

來源:互聯網
上載者:User

標籤:com   subject   pass   close   for   multi   lib   部分   def   

#! encoding:utf8‘‘‘ 環境:Win10 64位 Python 2.7.5參考:http://www.pythonclub.org/python-network-application/email-formathttp://blog.sina.com.cn/s/blog_4deeda2501016eyf.html‘‘‘import imaplibimport emaildef parseHeader(message):    """ 解析郵件首部 """    subject = message.get(‘subject‘)       h = email.Header.Header(subject)    dh = email.Header.decode_header(h)    subject = unicode(dh[0][0], dh[0][1]).encode(‘gb2312‘)    # 主題    print subject    print ‘</br>‘    # 寄件者    print ‘From:‘, email.utils.parseaddr(message.get(‘from‘))[1]    print ‘</br>‘    # 收件者    print ‘To:‘, email.utils.parseaddr(message.get(‘to‘))[1]    print ‘</br>‘# 抄送人    print ‘Cc:‘,email.utils.parseaddr(message.get_all(‘cc‘))[1]    def parseBody(message):""" 解析郵件/信體 """# 迴圈信件中的每一個mime的資料區塊for part in message.walk():    # 這裡要判斷是否是multipart,是的話,裡面的資料是一個message 列表    if not part.is_multipart():         charset = part.get_charset()        # print ‘charset: ‘, charset        contenttype = part.get_content_type()        # print ‘content-type‘, contenttype        name = part.get_param("name") #如果是附件,這裡就會取出附件的檔案名稱        if name:            # 有附件            # 下面的三行代碼只是為瞭解碼象=?gbk?Q?=CF=E0=C6=AC.rar?=這樣的檔案名稱            fh = email.Header.Header(name)            fdh = email.Header.decode_header(fh)            fname = dh[0][0]            print ‘附件名:‘, fname            # attach_data = par.get_payload(decode=True) # 解碼出附件資料,然後儲存到檔案中             # try:            #     f = open(fname, ‘wb‘) #注意一定要用wb來開啟檔案,因為附件一般都是二進位檔案            # except:            #     print ‘附件名有非法字元,自動換一個‘            #     f = open(‘aaaa‘, ‘wb‘)            # f.write(attach_data)            # f.close()        else:            #不是附件,是常值內容            print part.get_payload(decode=True) # 解碼出常值內容,直接輸出來就可以了。 # pass        # print ‘+‘*60 # 用來區別各個部分的輸出def getMail(host, username, password, port=993):try:serv = imaplib.IMAP4_SSL(host, port)except Exception, e:serv = imaplib.IMAP4(host, port)serv.login(username, password)serv.select()# 搜尋郵件內容typ, data = serv.search(None, ‘(FROM "[email protected]")‘)count = 1pcount = 1for num in data[0].split()[::-1]:    typ, data = serv.fetch(num, ‘(RFC822)‘)    text = data[0][1]    message = email.message_from_string(text)# 轉換為email.message對象    parseHeader(message)    print ‘</br>‘    parseBody(message)      pcount += 1    if pcount > count:    breakserv.close()serv.logout()if __name__ == ‘__main__‘:host = "imap.mail_serv.com" # "pop.mail_serv.com"username = "[email protected]_serv.com"password = "your_password"getMail(host, username, password)

 

轉自:https://my.oschina.net/dexterman/blog/177650

利用Python imaplib和email模組 讀取郵件常值內容及附件內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.