Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: save attachments from .msg files

So I have a folder with a ton of .msg files. I want to be able to save one of the attachments. My idea was automating clicking the files, then somehow extracting the file with a certain file name but I have yet to find any solutions to this.

How do I go about doing this? Or a better way?

Thanks!

Update: I've got an idea to use os.startfile to open the file I want it to open... How do I not open it in another window? But act like it did? If that makes any sense :/

like image 823
arthur6523 Avatar asked May 04 '17 15:05

arthur6523


2 Answers

This should work:

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

Since you say you have a folder, this will automate the whole folder:

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
like image 52
Harish Anjaneya Avatar answered Sep 30 '22 16:09

Harish Anjaneya


Adding to Harish answer because, for me, the method didn't work, as OpenSharedItem() requires an absolute path.

As such I recommend the following for an entire folder:

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
like image 25
Rui Rebelo de Andrade Avatar answered Sep 30 '22 16:09

Rui Rebelo de Andrade