lokheart
lokheart

Reputation: 24685

Creating folders in outlook 2010 using python

I know how to get the name of folders in outlook 2010 using the code below:

import win32com.client

ol = win32com.client.Dispatch("Outlook.Application")
ns = ol.GetNamespace("MAPI")
inbox = ns.Folders(6).Folders(2)

How can I add a folder in Folder(2)? I tried the Folders.Add Method method as mentioned in http://support.microsoft.com/kb/208520 but fail.

Upvotes: 3

Views: 2628

Answers (2)

Thom Ives
Thom Ives

Reputation: 3989

Adding Folders at the Top Level With Other Settings

The clear answer from @lowitty (owner voted as best answer) works well.

I leveraged from lowitty's answer to create both a sub-folder and a top-level-folder.

I also used settings that I've been using in my own development in case those will help others too.

Invoke the Python interpreter OR modify and run the below as a script:

>>> import win32com.client as win32
>>> import pythoncom
>>> app = win32.gencache.EnsureDispatch("Outlook.Application", pythoncom.CoInitialize())
>>> namespace = app.GetNamespace("MAPI")
>>> sent_folder = namespace.Folders["[email protected]"].Folders["Sent Items"]
>>> sent_folder.Name

'Sent Items'

>>> sent_folder.Folders.Add("Test")

<win32com.gen_py.Microsoft Outlook 16.0 Object Library.MAPIFolder instance at 0x2320338244592> 
# And created "Test" as a subfolder under the "Sent Items" folder.

>>> namespace.Folders["[email protected]"].Folders.Add("Hello")

<win32com.gen_py.Microsoft Outlook 16.0 Object Library.MAPIFolder instance at 0x2320338445712>
# And created a "Hello" folder at the top level.

Upvotes: 0

lowitty
lowitty

Reputation: 924

I think you have made a small mistake, the Add function is the function of Folders. Not a certain Folder like Folders(2)

You can try the code below and it should work:

import win32com.client

ol = win32com.client.Dispatch("Outlook.Application")
ns = ol.GetNamespace("MAPI")
inbox = ns.Folders(6).Folders(2)
inbox.Folders.Add("My Folder Src")

Upvotes: 5

Related Questions