Python: save attachments from .msg files

11,041

Solution 1

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

Solution 2

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
Share:
11,041
arthur6523
Author by

arthur6523

Updated on June 18, 2022

Comments

  • arthur6523
    arthur6523 almost 2 years

    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 :/