Reputation: 695
I would like to download multiple attachments from outlook. I have this code at this moment but have this problem.
In this pic:
you see that attachment
variable has problem.
Error: pywintypes.com_error: (-2147352567, 'Exception occurred.',
(4096, 'Microsoft Outlook', 'Array index out of bounds.', None, 0, -2147352567), None)
Code:
import datetime
import os
import win32com.client
path = ("C:/Users/greencolor/Desktop/Autoreport/")
today = datetime.date.today()
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
def saveattachemnts(subject):
for message in messages:
if message.Subject == subject and message.Unread or message.Senton.date() == today:
# body_content = message.body
attachments = message.Attachments
attachment = attachments.Item(1)
for attachment in message.Attachments:
attachment.SaveAsFile(os.path.join(path, str(attachment)))
if message.Subject == subject and message.Unread:
message.Unread = False
break
download = saveattachemnts('PB report - next steps')
Upvotes: 1
Views: 1854
Reputation: 12495
You cannot assign attachment
to attachments.Item(1)
then use it on for loop to iterating over message.Attachments
Try Example
import datetime
import os
import win32com.client
path = r"C:/Users/greencolor/Desktop/Autoreport/"
today = datetime.date.today()
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
def save_attachments(subject):
for message in messages:
if message.Subject == subject and message.Unread or message.Senton.date() == today:
for attachment in message.Attachments:
print(attachment.FileName)
attachment.SaveAsFile(os.path.join(path, str(attachment)))
if __name__ == "__main__":
save_attachments('PB report - next steps')
A better way would be to use filter
Items.Restrict(Filter)
https://stackoverflow.com/a/57931132/4539709
Upvotes: 1
Reputation: 66341
You are assuming the message has attachments and unconditionally accessing the very first attachment. You need to check that attachments.Count > 0
Upvotes: 0