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 :/
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With