I seem to be unable to use a Powershell variable to set the HTMLBody property of a new Outlook e-mail message. See below. The only difference is that in the second example, the desired HTML string is stored in a Powershell variable.
# this works fine.
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$mail.HTMLBody= "<html><head></head><body><p>Hello, World</p></body></html>"
$mail.save()
$inspector = $mail.GetInspector
$inspector.Display()
# this does not work. The email body remains empty
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$body = "<html><head></head><body><p>Hello, World</p></body></html>"
$mail.HTMLBody= $body
$mail.save()
$inspector = $mail.GetInspector
$inspector.Display()
I am using Powershell 5 and Outlook 2019 on Windows 10. What do I have to make the $body variable take effect?
It seems this is related how PowerShell treats string variables. The
HTMLBodyis a string property which contains HTML markup of the message body. From the Outlook object model point of view the code looks good.But I've noticed the following lines of code after setting the
HTMLBodyproperty:There is no need to get an instance of the
Inspectorclass to get the item displayed in Outlook. You could call the Display method of theMailItemclass instead.