0

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?

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Rno
  • 784
  • 1
  • 6
  • 16
  • 1
    I stumbled on a workaround: `$mail.HTMLBody= (Out-String -InputObject $body)` works. I have no idea why. – Rno Jan 08 '23 at 00:08
  • Fwiw, I couldn't reproduce this issue - the second code sample behaved exactly like the first and showed a message draft with "Hello World" in the body pane... – mclayton Jan 08 '23 at 20:19
  • @mclayton on another system I cannot reproduce it either. Very odd. – Rno Jan 09 '23 at 22:26

1 Answers1

0

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.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • I appreciate your suggestion but it is not an answer to the question. I agree that there seems to be some PS oddness going on - but what? – Rno Jan 08 '23 at 23:59
  • The post tells that the code looks good. From the Outlook object model point of view everything is good. The issue **may be** related to PowerShell syntax. – Eugene Astafiev Jan 09 '23 at 08:39