Cannot use Powershell variable to set Outlook HTMLBody property

289 Views Asked by At

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?

1

There are 1 best solutions below

2
Eugene Astafiev On

It seems this is related how PowerShell treats string variables. The HTMLBody is 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 HTMLBody property:

$inspector = $mail.GetInspector
$inspector.Display()

There is no need to get an instance of the Inspector class to get the item displayed in Outlook. You could call the Display method of the MailItem class instead.