I want to save outlook attachments from outlook with the following structure:
attach(on desktop) -->folder(name of subfolder in outlook)-->folder(individual message) --> attachments from message
I am coming across a problem where for some reason all attachments from a subfolder are saving into every message folder instead of just the message folder they belong.
Sorry if my code is redundant I just started learning!
import win32com.client as client
import os
outlook = client.Dispatch('Outlook.Application').GetNamespace('MAPI')
path = 'C:\\Users\\XXXXX\\Desktop\\Attach'
os.chdir(path)
inbox = outlook.GetDefaultFolder(6)
inboxfolders = inbox.Folders
inbxcount = inboxfolders.Count
folderlist = []
for x in range(1, inbxcount + 1):
subfolder = inboxfolders[f'{x}']
strsub = str(subfolder)
if 'PRs' in strsub:
folderlist.append(strsub)
for i in folderlist:
newfolder = i
os.makedirs(newfolder)
sub = inboxfolders[f'{i}']
messages = sub.Items
msgcount = messages.Count
newpath = f'{path}\\{newfolder}'
for y in range(1, msgcount + 1):
msgfolder = f'PR{y}'
os.chdir(newpath)
os.makedirs(msgfolder)
path3 = f'{newpath}\\PR{y}'
for msg in range(1, msgcount + 1):
message = messages.Item(msg)
attachments = message.Attachments
attchcount = attachments.Count
for attch in range(1, attchcount + 1):
attachment = attachments.Item(attch)
sattachment = str(attachment)
if 'image' not in sattachment:
attachment.SaveAsFile(os.path.join(path3, sattachment))
os.chdir(path)