'Cannot save the attachment' error when retrieving Outlook email

Question:

As of today I am receiving an error when attempting to save email attachments from Outlook using Python and win32com library.
This was previously working however since modifying the code to get only the latest emails, the attachments are no longer being saved to the specified location.

See code and comments below.

## Dependencies
import win32com.client
import os
from datetime import datetime, timedelta

## Aliases
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")

## Get accounts
for account in mapi.Accounts:
    print(account.DeliveryStore.DisplayName)

## Date parameters for filter
today = datetime.today()

start_time = today.replace(day=7).strftime('%Y-%m-%d %H:%M %p')

end_time = today.replace(hour=0, minute=0, second=0).strftime('%Y-%m-%d %H:%M %p')

## Retrieve mail
messages = mapi.Folders('me@my_email_address.com').Folders('Inbox').Items.Restrict("[ReceivedTime] >= '" + start_time
+ "' And [ReceivedTime] <= '" + end_time + "'")

messages = messages.Restrict("[Subject] = 'Really cool email'")

## Check output
for message in messages:
    print(message ,  "|" , message.ReceivedTime, "|",  attachment.FileName)

This last step shows the following. Note email attachment is present.

'FW: Really cool email | 2022-07-11 04:04:09.866000+00:00 | Really cool attachment.xlsx'
'FW: Really cool email | 2022-07-18 03:53:51.475000+00:00 | Really cool attachment.xlsx'

In the next step I iterate through the messages in order to extract the attachments and save them to the location I specify.

## Specify file destination path
outputDir = r"Z:My FolderReally Cool Data Folder"

## Save attachments
try:
    for message in list(messages):
        try:
            s = outputDir
            for attachment in message.Attachments:
                attachment.SaveASFile(os.path.join(outputDir, attachment.FileName))
                print(f"attachment {attachment.FileName} saved to {s} '")
        except Exception as e:
            print("error when saving the attachment:" + str(e))
except Exception as e:
        print("error when processing emails messages:" + str(e))

The error I get now is;

error when saving the attachment:
    (-2147352567, 'Exception occurred.',
        (4096, 'Microsoft Outlook', 'Cannot save the attachment.', None, 0,
         -2147024864), None)

I have not been able to discern why the attachment can not be save. As stated, this code was working as expected prior to the addition of some filtering to make the looping more efficient.

Note the error doesn’t mention anything about permissions or invalid file path.

Asked By: jimiclapton

||

Answers:

-2147024864 (0x80070020) translates to ERROR_SHARING_VIOLATION, which means the file you are trying to overwrite is being used.

Make sure you close Excel or at least the xlsx files files that are being overwritten.