1

Outlook.msg 本文をテキスト ファイルに抽出する

def getEmailBodyFromMsg():

mapi.MAPIInitialize ((mapi.MAPI_INIT_VERSION, 0)) 
storage_flags = win32com.storagecon.STGM_DIRECT | win32com.storagecon.STGM_READ | win32com.storagecon.STGM_SHARE_EXCLUSIVE 
filepathList = glob.glob('*.msg')

for filepath in filepathList :

    txtFilepath = os.path.splitext(ntpath.basename(filepath))[0]
    resultFile = txtFilepath + datetime.now().strftime('%Y-%m-%d %H_%M_%S')+".txt"

    #get body of email and save as txt
    storage = pythoncom.StgOpenStorage (filepath, None, storage_flags, None, 0) 
    mapi_session = mapi.OpenIMsgSession () 
    message = mapi.OpenIMsgOnIStg (mapi_session, None, storage, None, 0, mapi.MAPI_UNICODE)

    #write to txt file
    CHUNK_SIZE = 10000 
    stream = message.OpenProperty (win32com.mapi.mapitags.PR_BODY, pythoncom.IID_IStream, 0, 0) 
    text = u"" 
    while True: 
        bytes = stream.read (CHUNK_SIZE) 
        if bytes: 
            text += bytes
        else: 
            break 
    with codecs.open(resultFile, mode='w', encoding='utf-8') as a_file:
        a_file.write(text)

テキストを検索するために上記に書き込まれたファイルを開くと、行は次のようになります。

    with  codecs.open(absFilepath, 'rb', encoding='utf-8') as inFile :
        for index, line in enumerate(inFile) :
            mymatch =  re.search(csResultEmailPattern, line, re.UNICODE)

#line = 'R\x00e\x00s\x00u\x00l\x00t\x00s\x00 \x00f\x00r\x00o\x00m\x00\n' #OR line = u'R\x00e\x00s\x00u\x00l\x00t\ x00s\x00\x00f\x00r\x00o\x00m\x00\r'

上記の「Rx00e..line」に一致するresultEmailPattern = ur'Results'のような正規表現を指定する有効な方法であるか、またはtxtファイルをエンコードするより良い方法であるかどうかを知りたい

4

0 に答える 0