Moving Mail from one folder to another using message-id in outlook using win32com.clent

68 views Asked by At

I was trying to move email from one folder to another using message id. The code is mentioned below:

    def move_email_by_message_id(self, from_folder, to_folder, msg_id):
        try:
            # Get the specified source and target folders
            source_folder = self.outlook.GetNamespace("MAPI").Folders(self.username).Folders(from_folder)
            target_folder = self.outlook.GetNamespace("MAPI").Folders(self.username).Folders(to_folder)

            # Find the email by Message-ID in the source folder
            filter_str = "@SQL=" + f"urn:schemas:httpmail:message-id LIKE '%{msg_id}%'"
            items = source_folder.Items.Restrict(filter_str)
            
            if len(items) == 1:
                email = items[0]
                email.Move(target_folder)
                print(f"Email with Message-ID '{msg_id}' moved from '{from_folder}' to '{to_folder}' folder.")
            else:
                print(f"Email with Message-ID '{msg_id}' not found in '{from_folder}'.")

        except Exception as e:
            print("Error:", e)


I was getting the error that "Email with Message-ID not found in folder" .But actually that particular mail is present inside that folder. I cross verified it by checking the outlook and printing the msg id in the console. Please help me to fix this issue. Thanks in advance!!!

1

There are 1 answers

0
Dmitry Streblechenko On

The DASL property name must be quoted:

filter_str = f"@SQL=""http://schemas.microsoft.com/mapi/proptag/0x1035001F"" = '{msg_id}'"