admin管理员组

文章数量:1323175

To evade a general policy at our company that deletes Outlook tasks after 10 years independent of the last modified date, I tried to duplicate then delete the old tasks with Python. VBA is blocked per Cybersecurity Guideline.

I was unable to copy the body of tasks with images and files inline.

Apparently, TaskItem does not have an HTML Body. Can I copy RTFBody?

new_task.RTFBody = old_task.RTFBody

throws:

An error occurred: (-2147024809, 'The parameter is incorrect.', None, None)

I tried decoding the RTFBody content with:

rtf_data = bytes(old_task.RTFBody)
rtf_content = rtf_data.decode('utf-8', errors='ignore')

I have not much of an idea what the decoded content means. Let alone I don't know why that would make sense - in the end I have to pass the binary data back to the new task, don't I?

Complete code.

import win32com.client
import tempfile
import os
import shutil

def duplicate_and_delete_tasks():
    try:
        outlook = win32com.client.Dispatch("Outlook.Application")
        namespace = outlook.GetNamespace("MAPI")

        tasks_folder = namespace.GetDefaultFolder(13)

        original_tasks = [task for task in tasks_folder.Items if task.Class == 48]

        for task in original_tasks:
            print("Task being processed: " + task.Subject)
            new_task = tasks_folder.Items.Add("IPM.Task")
            new_task.Subject = task.Subject
            try:
                new_task.RTFBody = task.RTFBody
            except:
                new_task.Body = task.Body
            new_task.StartDate = task.StartDate
            new_task.DueDate = task.DueDate
            new_task.Categories = task.Categories
            new_task.Importance = task.Importance
            new_task.Status = task.Status
            # if task.Attachments.Count > 0:
            #     temp_dir = tempfile.mkdtemp()
            #     for attachment in task.Attachments:
            #         try:
            #             attachment.SaveAsFile(os.path.join(temp_dir, attachment.FileName))
            #             new_task.Attachments.Add(os.path.join(temp_dir, attachment.FileName))
            #         except:
            #             pass
            #     shutil.rmtree(temp_dir)
            new_task.Save()
            print("New task created.")
            task.Delete()
            print("Old task deleted.")

        print("All tasks have been successfully processed.")

    except Exception as e:
        print(f"An error occurred: {e}")

duplicate_and_delete_tasks()

本文标签: pythonCopy RTF Body of Outlook TaskStack Overflow