Проблема с Action.AssignToCategory, использующим Python для создания правил OutlookPython

Программы на Python
Гость
Проблема с Action.AssignToCategory, использующим Python для создания правил Outlook

Сообщение Гость »


У меня есть скрипт Python для создания правил Outlook на основе некоторых данных в электронной таблице Excel (название правила, адрес, папка для перемещения и категория).
Я был в состоянии получить

Код: Выделить всё

MoveToFolder
action to work, but can't figure out the

Код: Выделить всё

AssignToCategory
one.
This is what the data in the excel file looks like. I bring it in as a list of strings (1 string per row) and use split to get the individual values.
Изображение
Here is the Python script:

Код: Выделить всё

import comtypes.client as cc
import Read_Excel as xl

# Get details for rules to create from Excel File
rules_to_proces = xl.load_rules(r"C:\Users\myname\Documents\Outlook_Rules.xlsx")

# Create Outlook object
olApp = cc.CreateObject("Outlook.Application")

# Get Outlook collection of rules
olRules = olApp.Session.DefaultStore.GetRules()

# Get Account address
olAccount = olApp.GetNamespace('MAPI').Accounts.Item(1).DisplayName

# For each rule pulled in from the Excel file
for pRule in rules_to_proces:

# Set the rule name, from email address, folder/s and category based on data pulled in from Excel
olRuleName = pRule.split(';')[0]
olRuleAddress = pRule.split(';')[1]
olRuleFolder = pRule.split(';')[2]
olRuleCategory = pRule.split(';')[3]

# Create a new rule in the Outlook rules collection
olRule = olRules.Create(olRuleName, 0)

# Set the from condition to the email address and name of the sender and enable the condition
olFromCondition = olRule.Conditions.From
olFromCondition.Enabled = True
olFromCondition.Recipients.Add(olRuleAddress)
olFromCondition.Recipients.Add(olRuleName)
olFromCondition.Recipients.ResolveAll

# Set the root folder for the account
olRootFolder = olApp.GetNamespace('MAPI').Folders.Item(olAccount)

# Get a count of how many folders deep the string from Excel file has
# i.e.  Входящие/Папка = 2, Входящие/Папка/Папка = 3 и т. д.
olFolderCount = len(olRuleFolder.split('/'))

# Установите папку назначения глубиной до 5 папок, в зависимости от olFolderCount
if olFolderCount == 1:
olDestinationFolder = olRootFolder\
.Folders[olRuleFolder.split(r'/')[0]]
elif olFolderCount == 2 :
olDestinationFolder = olRootFolder\
.Folders[olRuleFolder.split(r'/')[0]]\
.Folders[olRuleFolder.split(r'/')[1]]
elif olFolderCount == 3:
olDestinationFolder = olRootFolder\
.Folders[olRuleFolder.split(r'/')[0]]\
.Folders[olRuleFolder.split( r'/')[1]]\
.Folders[olRuleFolder.split(r'/')[2]]
elif olFolderCount == 4:
olDestinationFolder = olRootFolder\
.Folders[olRuleFolder.split(r'/')[0]]\
.Folders[olRuleFolder.split(r'/')[1]]\
.Folders[olRuleFolder.split (r'/')[2]]\
.Folders[olRuleFolder.split(r'/')[3]]
elif olFolderCount == 5:
olDestinationFolder = olRootFolder\< br /> .Folders[olRuleFolder.split(r'/')[0]]\
.Folders[olRuleFolder.split(r'/')[1]]\
.Folders[olRuleFolder. Split(r'/')[2]]\
.Folders[olRuleFolder.split(r'/')[3]]\
.Folders[olRuleFolder.split(r'/')[ 4]]
else:
print("Дерево папок слишком глубокое.")

# Включить действие перемещения в папку, установить значение «включено» и установить папку назначения
olMove = olRule.Actions.MoveToFolder
olMove.__MoveOrCopyRuleAction__com__set_Enabled(True)
olMove.__MoveOrCopyRuleAction__com__set_Folder(olDestinationFolder)

# ниже показано, что вызывает ошибку
# включить присвоение категории действие, установите значение «включено» и установите категорию для назначения
olCategory = olRule.Actions.AssignToCategory
olCategory.__AssignToCategoryRuleAction__com__set_Enabled(True)
olCategory.__AssignToCategoryRuleAction__com__set_Categories(olRuleCategory)

# сохраняем коллекцию правил с добавленным новым правилом
olRules.Save()

Вывод ошибки:
< бр />

Код: Выделить всё

Traceback (most recent call last):
File "C:\Users\myname\PycharmProjects\pythonProject1\Outlook2.py", line 79, in 
olCategory.__AssignToCategoryRuleAction__com__set_Categories(olRuleCategory)
_ctypes.COMError: (-2147352571, 'Type mismatch.', (None, None, None, 0, None))

Process finished with exit code 1

The Action.AssignToCategory.Categories object type is tuple.
If I just add tuple, I get a slightly different error:

Код: Выделить всё

Traceback (most recent call last):
File "C:\Users\myname\PycharmProjects\pythonProject1\Outlook2.py", line 79, in 
olCategory.__AssignToCategoryRuleAction__com__set_Categories(tuple(olRuleCategory))
_ctypes.COMError: (-2147024809, 'The parameter is incorrect.', ('Sorry, something went wrong. You may want to try again.', 'Microsoft Outlook', None, 0, None))

Process finished with exit code 1
I'm still very new to python so this is really melting my brain. Any help that can be offered would be greatly appreciated?
I've tried as many different versions as I can think of/find online such as:

Код: Выделить всё

olCategory.__AssignToCategoryRuleAction__com__set_Categories(**[**olRuleCategory**]**)

olCategory.Categories = olRuleCategory

olCategory.Categories = **[**olRuleCategory**]**

olRuleCategory = tuple(olRuleCategory)
The way below results in the code executing without error, but there is nothing in the rule about the category.

Код: Выделить всё

olCategory.__AssignToCategoryRuleAction__com__set_Enabled = True
olCategory.__AssignToCategoryRuleAction__com__set_Categories = olRuleCategory


Источник: https://stackoverflow.com/questions/781 ... look-rules

Вернуться в «Python»