Skip to content
Advertisement

Python adding outlook color categories to specific emails with a loop

I am trying to add color categories to existing emails in a given outlook folder based on criterias such as email object and/or sender email address.

import win32com.client as client
import win32com
import pandas as pd

outlook = client.Dispatch("Outlook.Application").GetNamespace('MAPI')

main_account = outlook.Folders.Item(1)
second_account = outlook.Folders.Items(3)

df = pd.read_excel (r'C:Pythontest.xls')

df_outlook_folder = df['Outlook_folder'].tolist()
df_mail_object = df['Mail_object'].tolist()

out_iter_folder = main_account.Folders['Inbox'].Folders['TEST']

fixed_item_count = out_iter_folder.Items.Count
item_count = out_iter_folder.Items.Count

if yout_iter_folder.Items.Count > 0:
    for i in reversed(range(0,item_count)):
        message = out_iter_folder.Items[i]
        for y,z in zip(df_mail_object,df_outlook_folder):
            try:
                if y in message.Subject:
                     message.Move(second_account.Folders['Inbox'].Folders['TESTED'].Folders[z]
            except:
                pass
item_count = out_iter_folder.Items.Count
print('Nb mails sorted:',fixed_item_count - item_count)

the code above enables me to move emails based on the mail object but I am not able so far to add a feature to also change the outlook color categories

I spent time on the following doc without success so far https://learn.microsoft.com/en-us/office/vba/api/outlook.categories

Advertisement

Answer

Categories is a delimited string of category names that have been assigned to an Outlook item.

mail.Categories='Red category'
mail.Save()

You may find the update categories in emails using python thread helpful.

Advertisement