Home > Software design >  edit body of .msg outlook Python
edit body of .msg outlook Python

Time:07-29

I'm trying to replace the word "interface" with "test" in the outlook template (.msg). I'm able to replace the body but it does not edit the template .msg. The goal is to see the word "test" instead of"Interface" when I do the template_six.display(). The template is in read only mode

import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
find_in_email_6 = "Interface"
template_six = outlook.OpenSharedItem(r"\\users\Email 6.msg")
body = template_six.Body
replace_six=body.replace("Interface","test")

if find_in_email_6 in body:
    replace_six
    print(template_six.Body)#display interface
    print(replace_six)#display test
    template_six.display()

CodePudding user response:

I finally found, have to use HTMLBody, here the code :

template_six = outlook.OpenSharedItem(r"\\users\Email 6.msg")
new_template_six = template_six
body = template_six.HTMLBody
if find_in_email_6 in body:
            new_template_six.HTMLBody = body.replace ("Interface","test")
            new_template_six.display()

I have to find how to remove read only before display now :)

CodePudding user response:

Use the Application.CreateItemFromTemplate method which creates a new Microsoft Outlook item from an Outlook template (.oft) and returns the new item.

import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
find_in_email_6 = "Interface"
template_six = outlook.CreateItemFromTemplate(r"\\users\Email 6.msg")
body = template_six.HTMLBody
replace_six=body.replace("Interface","test")

if find_in_email_6 in body:
    replace_six
    print(template_six.HTMLBody)#display interface
    print(replace_six)#display test
    template_six.display()

You can read more about that method in the How To: Create a new Outlook message based on a template article.

  • Related