Opening files with spaces with outlook.OpenSharedItem is giving error
Asked Answered
G

3

1

I got the following code:

import win32com.client
import os

directory = "C:/Users/mypath/"
for filename in os.listdir(directory):
    _, file_extension = os.path.splitext(filename)
    if file_extension == ".msg":  
        print(filename)
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        msg = outlook.OpenSharedItem(directory + filename)
        att=msg.Attachments
        for i in att:
            i.SaveAsFile(os.path.join(directory, i.FileName))
        del outlook, msg

This code extracts the files attached to a .msg and when I run it, I got the following output:

ATP-3770289.msg ATP-5126209.msg ATP-5126317.msg ATT -1937501.msg com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', "We can't open 'C://Users/omar.lopez.rubio/Desktop/admisiones/ATT%20-1937501.msg'. It's possible the file is already open, or you don't have permission to open it.\n\nTo check your permissions, right-click the file folder, then click Properties.", None, 0, -2147287038), None)

Which is caused obviously because

ATT -1937501.msg

has a space. I'm running this on Spyder in windows. Any clues how to solve this? Thanks.

Gemmulation answered 29/6, 2018 at 8:45 Comment(0)
C
2

close your outlook while running the python program

Cragsman answered 10/7, 2018 at 16:54 Comment(1)
Did you ever find an answer for this??Helen
G
1

The solution that worked for me was found in a comment by @smartexpert on this question. The OpenSharedItem method expects an absolute file path, not a relative file path. Once I changed all the .msg file paths to absolute paths, I stopped getting this error. It looks like this may not be your specific problem, since your error includes an absolute path, but I thought I should put my experience somewhere it might help others who have similar errors.

Gaullist answered 30/11, 2023 at 19:43 Comment(0)
O
0

I was in the same situation, in my case it was that the files had space in the name.

Python does not work with spaces.

import win32com.client
import os
path = 'C:/testes/mail'
files = [f for f in os.listdir(path) if '.msg' in f]
for file in files:
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    msg = outlook.OpenSharedItem(os.path.join(path, file))
    att=msg.Attachments
    for i in att:
        i.SaveAsFile(os.path.join('C:/testes/email_download', i.FileName))
Ouzel answered 22/2, 2020 at 17:24 Comment(1)
"Python does not work with spaces" - this is just nonsense.Unexpressed

© 2022 - 2025 — McMap. All rights reserved.