【问题标题】:Extracting .xlsx attachments from .msg files从 .msg 文件中提取 .xlsx 附件
【发布时间】:2020-02-19 20:37:47
【问题描述】:

我知道这已经被问过好几次了,我已经尝试过显然对其他人有用的方法...我有 1000 多个带有 .xlsx 文件附件的 Outlook .msg 文件存储在我桌面上的文件夹中,我只需要提取 .xlsx 文件以组合成单个数据帧。

我已经尝试过VBA macro、Python [Win32] (Parsing outlook .msg files with python) 和msg-extractor。我能做的最好的就是从单个 .msg 文件中提取单个附件

非常感谢任何建议。谢谢!

import argparse
import csv
import os as os
import pathlib
import sys
from datetime import date, datetime, timedelta, tzinfo
from enum import Enum, IntEnum
from tempfile import mkstemp

import dateutil.parser as duparser
from dateutil.rrule import rrulestr, rruleset
import pywintypes
import pytz
import win32com.client  

path = r'C:\Users\Me\Desktop\MyFiles\feb_2018'
files = [f for f in os.listdir(path) if '.msg' in f]
print (files)
for file in files:
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    msg = outlook.OpenSharedItem(os.path.join(path, file))
    att=msg.Attachments
    for i in att:
        i.SaveAsFile(os.path.join(path, i.FileName))       


【问题讨论】:

  • VBA 宏似乎效果最好,但只提取 1 个文件,代码中是否有我遗漏的命令?

标签: python vba attachment data-extraction


【解决方案1】:

谢谢!我实际上想出了一个解决方案,通过包含一个计数器来使用 Win32 提取多个文件:

   path = r'C:\Users\filepath' #change path to directory where your msg files are located
   files = [f for f in os.listdir(path) if '.msg' in f]
   print (files)
   counter=0
   for file in files:
       outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
       msg = outlook.OpenSharedItem(os.path.join(path, file))
       att=msg.Attachments
       for i in att:
           counter +=1
           i.SaveAsFile(os.path.join(path, str(counter)+i.FileName))

【讨论】:

    【解决方案2】:

    我没有尝试使用 win32com 保存附件,所以我不知道为什么只有一个文件中的一个附件被保存。但我可以使用msg-extractor保存多个附件

    import extract_msg
    
    for file in files:
        msg = extract_msg.Message(file)
        msg_attachment = msg.attachments
        attach_path = "path where the files have to be saved."
        for attachment in msg_attachment:
            if not os.path.exists(attach_path):
                os.makedirs(attach_path)
            attachment.save(customPath=attach_path)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      相关资源
      最近更新 更多