2017-05-04 158 views
2

所以我有一大堆.msg文件的文件夾。我希望能夠保存其中一個附件。我的想法是自動點擊文件,然後以某種方式提取具有特定文件名的文件,但我還沒有找到任何解決方案。Python:保存.msg文件中的附件

我該如何去做這件事?還是更好的方法?

謝謝!

更新: 我有一個想法,使用os.startfile打開文件,我想打開它... 我怎麼不打開它在另一個窗口?但像這樣行事?如果這是有道理的:/

+0

這個問題可能對您有所幫助:HTTP:/ /stackoverflow.com/questions/9937664/how-to-extract-attachments-from-msg-files – Sevyns

+0

我看到這個文件!不幸的是,我已經有一個文件夾中的msg文件。所以它不直接與前景互動 – arthur6523

回答

1

我不確定這是否會解決您的問題,但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))) 
0

這應該工作:

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