1. 程式人生 > >Python讀取郵箱中的郵件,含文字,附件

Python讀取郵箱中的郵件,含文字,附件

#-*- encoding: utf-8 -*-
import sys
import locale
import poplib
from email import parser
import email
import string

# 確定執行環境的encoding
__g_codeset = sys.getdefaultencoding()
if "ascii"==__g_codeset:
    __g_codeset = locale.getdefaultlocale()[1]
#

def object2double(obj):
    if(obj==None or obj==""
): return 0 else: return float(obj) #end if # def utf8_to_mbs(s): return s.decode("utf-8").encode(__g_codeset) # def mbs_to_utf8(s): return s.decode(__g_codeset).encode("utf-8") # host = 'pop.exmail.qq.com' username = '[email protected]' password = 'password'
pop_conn = poplib.POP3_SSL(host) 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)] #print messages #print "--------------------------------------------------" # Concat message pieces: messages = ["\n"
.join(mssg[1]) for mssg in messages] #print messages #Parse message intom an email object: # 分析 messages = [parser.Parser().parsestr(mssg) for mssg in messages] i = 0 for index in range(0,len(messages)): message = messages[index]; i = i + 1; 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') mailName = "mail%d.%s" % (i, subject) f = open('%d.log'%(i), 'w'); 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 print >> f, "Data: " 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: data = part.get_payload(decode=True) h = email.Header.Header(fileName) dh = email.Header.decode_header(h) fname = dh[0][0] encodeStr = dh[0][1] if encodeStr != None: fname = fname.decode(encodeStr, mycode) #end if fEx = open("%s"%(fname), 'wb') fEx.write(data) fEx.close() elif contentType == 'text/plain':# or contentType == 'text/html': #儲存正文 data = part.get_payload(decode=True) content=str(data); if mycode=='gb2312': content= mbs_to_utf8(content) #end if nPos = content.find('降息') print("nPos is %d"%(nPos)) print >> f, data #end if #end for f.close() #end for pop_conn.quit()

相關推薦

Python讀取郵箱郵件文字附件

#-*- encoding: utf-8 -*- import sys import locale import poplib from email import parser import email import string # 確定執行環境的encod

python 讀取資料庫的BLOB型別欄位並存儲檔案到本地

import os import cx_Oracle os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' db_orcl = cx_Oracle.connect("使用者/[email protected]/orcl"

python讀取pdf文字

python處理pdf也是常用的技術了,對於python3來說,pdfminer3k是一個非常好的工具。 pip install pdfminer3k 我主要是想在pdf中抽出自己想要的一些關鍵資訊,所以需要找到這些資訊的共同點。幸運的是,這些關鍵資訊的行都含有'//',所以我只需找到含有'

python讀取xml資料庫中表內所有資料獲取資料庫所有表的欄位名稱

工作中需要讀取指定xml資料庫中的資料以及 表所需欄位名,所以在已有例子中改進實現: xml 資料庫 xmldabase.xml: <database> <manifest> <pair key="schema_major_vsn" v

python 讀取excel單元格的內容

                              python 讀取excel中單元格的內容    excel檔

python 在列表新增元組元素按照元組第一個值進行排序

  >>> import bisect >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')] >>> bisect.insort(scores,

http傳遞base64字串‘+’符號自動變成空格的問題

今天遇到base64加密向後端傳值的問題,本來經過加密已經傳過去了,但是沒有返回成功的結果。於是,與後端同事配合,找找問題所在。發現是加密後的字串中有一個“+”符號,在傳之前console.log了一下,是顯示這個符號的,但是傳輸過去在去識別,就換成空格了。在網上找到的大神們的做法,看到一個簡潔有效

python 從陣列隨機選擇一部分取出並從原陣列刪除取出的內容

可以使用numpy中的random.choice函式隨機選擇陣列的下標 numpy.random.choice(a, size=None, replace=True, p=None) #a為一維陣列或int值,為一維陣列時會從該陣列中隨機選擇元素,為int

python讀取的json再重新寫入會出現中文變成unicode碼

有一個表中的欄位 是gbk格式,比如該欄位是comment:這是人和公園的西門 然後 將該欄位 要插入另一個表(utf8)中的某個欄位:該欄位是個json, 往該json中添 加一個新的欄位commen

Python 計算字串所有數字的和如:'12abc34de5f' => 12 + 34 + 5 => 51

Python 計算字串中所有數字的和,如:‘12abc34de5f’ => 12 + 34 + 5 => 51 解題思路: 可以把不是數字的元素轉換成’ '空格, 然後按空格切割成列表, 把列表中的數字元素找出相加 最後返回 s = '12abc34de5f' def sum

python讀取兩個csv文件數據進行查找匹配出現次數

def port utf-8 true csv enc pen qrc closed 現有需求 表1 表2 需要拿表1中的編碼去表2中的門票編碼列匹配,統計出現的次數,由於表2編碼列是區域間,而且列不是固定的,代碼如下 #encoding:utf-8 #

python讀取sql裡面的指定資料列並將其轉換成列表使用

程式碼如下: import pyodbc import pandas as pd import numpy as np conn = pyodbc.connect(r'DRIVER={SQL Server Native Client 10.0};SERVER=.;DATABASE=資料庫名字

Python 讀取檔案unicode編碼轉成中文顯示問題

Python讀取檔案中的字串已經是unicode編碼,如:\u53eb\u6211,需要轉換成中文時有兩種方式 1.使用eval eval("u"+"\'"+unicodestr+"\'") 2.使用decode: str1 = '\u4f60\u

iOS 開發tabBarItem不顯示文字只顯示圖片且圖片居中顯示

//第一頁 HomePageViewController *homePageVC = [[HomePageViewControlleralloc] init]; UINavigationCon

python讀取excel中表結構生成sql語句存入txt檔案

python-excel-sql-txt#coding=utf-8 from openpyxl import load_workbook #讀取excel的資料 def read_excel(): #開啟一個workbook wb = load_workboo

python讀取檔案的一行有效資料

資料格式: t1.txt 1 1123 1y211 121&*dd99 0000 01 23 0111 993 d 984 程式碼: total =

python讀取csv所遇到的中文編碼問題

由於本人準備學習使用一些機器學習演算法,第一個是DecisionTree,然後使用到了西瓜案例: 因為涉及到討厭的編碼問題,所以找了好多辦法去嘗試讀取csv檔案: 1. pandas pandas可謂是神奇,用python學習機器學習不可缺

Tom郵箱郵件隨心隨意2019“豬”事順利

-o 安全 思考 一個人 如何 幫助 text 用戶需求 重要 春節喜慶的氛圍剛剛過去一周,各行各業逐漸投入緊張的忙碌中,今天元宵節過後,過年的氣氛圓滿收尾,如何去實現自己新一年的業績flag,將是持續思考的話題,TOM郵箱提醒您,郵件辦公千萬條,隨心收發第一條。 互聯網發

Python-SMTP發送郵件(HTML、圖片、附件)

finall 並發 前言 multipart art pre zhang imei lena 前言: SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協議,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。 一、P

二維碼生成包含文字網址圖片等

二維碼所引入的jar包 pom檔案配置         <dependency>