I want to send an HTML-Email with Powershell and the Send-MailMessage
Function. To keep my Code lightweigt, I have placed the HTML-Code for the Mailbody outside my Powershell-Code.
The challange is, to replace the Varibales inside the HTML-File with Powershell variables before sending the E-Mail.
The code here is not complete. I have shortened it to clarify the problem.
body.htm
<html>
<body>
<h1> Hello $Salutation! </h1>
</body>
</html>
myscript.ps1
$MailBody = Get-Content body.htm -Raw
$Salutation = "Foo Bar!"
$MailMessageParam = @{
"Subject" = "Mail from Powershell!"
"Encoding" = "UTF8"
"Body" = $MailBody
"BodyAsHtml" = $true
}
Send-MailMessage @MailMessageParam
My Problem is, that the Variable $Salutation
will not be filled. The $MailBody
Variables behaves like a Passthrough. Any idea how to solve this?
CodePudding user response:
One solution I can think of is to replace the $Salutation
with a placeholder and use the format operator to format it. So change body.htm to
<html>
<body>
<h1> Hello {0}! </h1>
</body>
</html>
And then in the hashtable($MailMessageParam
) set,
"Body" = ($MailBody -f $Salutation)
Alternatively you can just use ExpandString
method which returns a string with all of the variable and expression substitutions done.
"Body" = $ExecutionContext.InvokeCommand.ExpandString($MailBody)
CodePudding user response:
Awesome! $ExecutionContext.InvokeCommand.ExpandString($MailBody)
solved it!