使用win32com设置属性

时间:2011-08-17 07:57:43

标签: python outlook win32com

我正在尝试自动创建一堆Outlook规则。我正在使用Python 2.7,win32com和Outlook 2007.为此,我必须创建一个新的Rule对象并为其移动操作指定一个文件夹。但是,我无法成功设置Folder属性 - 尽管我提供了正确类型的对象,它仍然保持None。

import win32com.client
from win32com.client import constants as const

o = win32com.client.gencache.EnsureDispatch("Outlook.Application")
rules = o.Session.DefaultStore.GetRules() 

rule = rules.Create("Python rule test", const.olRuleReceive) 
condition = rule.Conditions.MessageHeader 
condition.Text = ('Foo', 'Bar')
condition.Enabled = True

root_folder = o.GetNamespace('MAPI').Folders.Item(1)
foo_folder = root_folder.Folders['Notifications'].Folders['Foo']

move = rule.Actions.MoveToFolder
print foo_folder
print move.Folder
move.Folder = foo_folder
print move.Folder

# move.Enabled = True
# rules.Save()

打印

<win32com.gen_py.Microsoft Outlook 12.0 Object Library.MAPIFolder instance at 0x51634584>
None
None

在非动态模式下使用win32com时,我查看了makepy生成的代码。课程_MoveOrCopyRuleAction在其'Folder'字典中有一个_prop_map_put_条目,但除此之外我感到难过。

2 个答案:

答案 0 :(得分:1)

尝试SetFolder()

我想从粗略阅读你的代码尝试SetFolder(move,foo_folder)

win32com做了一些神奇的魔术但有时COM对象只是打败了它。 当对象不能遵循pythonic约定时,在幕后创建一个setter和getter,形式为Set {name} Get {name}

见:http://permalink.gmane.org/gmane.comp.python.windows/3231 NB - Mark Hammonds如何调试com是无价的 - 这些东西只是隐藏在usegroups中......

答案 1 :(得分:1)

使用comtypes.client代替win32com.client,您可以执行以下操作:

import comtypes.client

o = comtypes.client.CreateObject("Outlook.Application")
rules = o.Session.DefaultStore.GetRules() 

rule = rules.Create("Python rule test", 0 ) # 0 is the value for the parameter olRuleReceive
condition = rule.Conditions.Subject # I guess MessageHeader works too
condition.Text = ('Foo', 'Bar')
condition.Enabled = True

root_folder = o.GetNamespace('MAPI').Folders.Item(1)
foo_folder = root_folder.Folders['Notifications'].Folders['Foo']

move = rule.Actions.MoveToFolder
move.__MoveOrCopyRuleAction__com__set_Enabled(True) # Need this line otherwise 
                                                    # the folder is not set in outlook
move.__MoveOrCopyRuleAction__com__set_Folder(foo_folder) # set the destination folder

rules.Save() # to save it in Outlook

我知道它不是win32com.client,而是IronPython也没有!