使用win32com设置属性

6 投票
2 回答
3714 浏览
提问于 2025-04-16 23:46

我正在尝试自动创建一些Outlook规则。我使用的是Python 2.7、win32com和Outlook 2007。为了做到这一点,我必须创建一个新的规则对象,并指定一个文件夹来进行移动操作。然而,我无法成功设置文件夹属性——尽管我提供了正确类型的对象,它还是显示为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在它的_prop_map_put_字典中有一个'Folder'的条目,但除此之外我就不知道该怎么做了。

2 个回答

2

试试 SetFolder()

我觉得从你代码的表面来看,可以试试 SetFolder(move, foo_folder)

win32com 真的很神奇,但有时候 COM 对象会让它无能为力。 当对象无法遵循 Python 的常规用法时,后台会自动创建一个设置器和获取器,形式是 Set{name} 和 Get{name}

详情请见:http://permalink.gmane.org/gmane.comp.python.windows/3231 另外,Mark Hammonds 的调试 COM 的方法非常宝贵,这些内容在用户组中是隐藏的……

2

使用 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 实现的!

撰写回答