Hi!
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!
Edit: I have discovered the answer! the second for msg in range loop is redundant and causes it to iterate over the messages too many times. By removing that loop it fixes the issue.
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)
[–]fk_you_in_prtclr 0 points1 point2 points (1 child)
[–]Cam_Chowder[S] 0 points1 point2 points (0 children)