I am looping through the messages in a large mailbox to save attachments in a local folder. After a large number of attachments have been saved, I get the following error: Your server administrator has limited the number of items you can opensimultaneously.
Is there a way to prevent this? I have tried setting the attachment to None after saving, closing the email with message.Close(0/1) and changing the cached settings of the shared mailbox.
for message in list(messages):
for attachment in message.Attachments:
attachment_name = str(attachment)
if re.search('(.xlsx|.csv|.xls)',attachment_name):
if attachment_name in attachment_list:
no = no+1
attachment_name = str(no) + ' ' + attachment_name
attachment.SaveASFile(path+ '\\' + attachment_name)
print(attachment_name, 'saved from mail', message)
attachment_list.append(attachment_name)
else:
attachment.SaveASFile(path+ '\\' + attachment_name)
print(attachment_name, 'saved from mail', message)
attachment_list.append(attachment_name)
attachment.Close(1)
else:
pass
message.Close(1)
Your server administrator has limited the number of items you can opensimultaneously.
This is a good indicator that you keep multiple COM objects running in memory even when you are done working with them. I'd recommend releasing all underlying object timely.
Python objects are released when there are no more references to the object.
Rebinding obj to None would decrease the reference count to the object, and so would del obj. In both cases, the instance would be cleared if obj was the last reference to it.
The difference then is how you can use obj afterwards. Rebinding retains the variable (it is now bound to None), del removes it altogether and you'd get a NameError. What you pick is your choice, it won't have influence on how the instance is cleared from memory.
Read more about that on the Python how to release the memory for class object after processing it? page.