python使用imap接收郵件的過程探索html
https://www.cnblogs.com/yhlx/archive/2013/03/22/2975817.htmlpython
#! encoding:utf8 ''' 環境: Win10 64位 Python 2.7.5 參考: http://www.pythonclub.org/python-network-application/email-format http://blog.sina.com.cn/s/blog_4deeda2501016eyf.html ''' import imaplib import email def 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 "xx@xxx.com")') count = 1 pcount = 1 for 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: break serv.close() serv.logout() if __name__ == '__main__': host = "imap.mail_serv.com" # "pop.mail_serv.com" username = "Trevor@mail_serv.com" password = "your_password" getMail(host, username, password)
參考:https://my.oschina.net/dexterman/blog/177650app