Python:保存.msg文件中的附件

时间:2017-05-04 15:40:39

标签: python email pdf extract

所以我有一个包含大量.msg文件的文件夹。我希望能够保存其中一个附件。我的想法是自动点击文件,然后以某种方式提取具有特定文件名的文件,但我还没有找到任何解决方案。

我该怎么做呢?还是更好的方式?

谢谢!

更新: 我有一个想法,使用os.startfile打开我想要打开的文件... 我怎么不在另一个窗口打开它?但就像它一样吗?如果这有任何意义:/

3 个答案:

答案 0 :(得分:2)

这应该有效:

import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem(filename)        #filename including path
att=msg.Attachments
for i in att:
    i.SaveAsFile(os.path.join(Pathname, i.FileName))#Saves the file with the attachment name

由于您说您有一个文件夹,这将自动化整个文件夹:

import win32com.client
import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for file in files:
    if file.endswith(".msg"):
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        msg = outlook.OpenSharedItem(file)        
        att=msg.Attachments
        for i in att:
            i.SaveAsFile(os.path.join(Pathname, i.FileName))#Saves the file with the attachment name

答案 1 :(得分:1)

添加到Harish答案中是因为,对我而言,该方法不起作用,因为OpenSharedItem()需要绝对路径。

因此,我建议对整个文件夹执行以下操作:

import win32com.client
import os
inputFolder = r'.' ## Change here the input folder
outputFolder = r'.' ## Change here the attachments output folder

for file in os.listdir(inputFolder):
    if file.endswith(".msg"):
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        filePath = inputFolder  + '\\' + file
        msg = outlook.OpenSharedItem(filePath)
        att = msg.Attachments
        for i in att:
            i.SaveAsFile(os.path.join(outputFolder, i.FileName))#Saves the file with the attachment name

答案 2 :(得分:0)

我不确定这是否能解决您的问题,但Python附带email.parser。这至少可以帮助您阅读msg文件(假设它的格式正确)

import email
with open('/path/to/your/file.msg') as fl:
    msg = email.message_from_file(fl)

这将为您提供Message个对象。您应该能够使用msg.walk()获取该文件,该文件将为您提供所有附加内容。

for part in msg.walk():
    if part.get_content_type() == "image/png":
        with open('out.png', 'w') as fl:
            fl.write(part.get_payload(decode=True)))
相关问题