user4317867
user4317867

Reputation: 2448

Creating Outlook HTML table from PSCustomObject

I've got a PSCustomObject $result which contains data that I filter through with the purpose of creating an HTML table that will be sent via Send-MailMessage.

I can create an HTML table that looks great but I'm trying to insert this table into the body of an Outlook email, which does not seem to work with the CSS because in Outlook Word does the rendering (from what I read). If simply attaching the htm file to the email is my only option, I'll go that route but my preference is inserting the table into the email body.

$denied = @()
foreach ($a in $result) {
  if ($a.MaintenanceWindow -eq 'Not found!' -or $a.LastReboot -eq 'Access Denied!') {
    $denied += $a
 }

} #end foreach

$a = @'
"<style>"
"BODY{background-color:lightgrey;}"
"TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
"TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
"TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
"</style>"
'@

$denied | ConvertTo-Html -Head $a | Out-File D:\c.htm;
ii D:\c.htm

Upvotes: 0

Views: 1778

Answers (1)

Matt
Matt

Reputation: 46710

If you want the table as the body of the email that is easily done.

# -Body expects one string. Out-String will take care of that. 
$HTMLBody = $denied | ConvertTo-Html -Head $a | Out-String
# To be sure it is rendered as HTML we use the switch -BodyAsHTML
Send-MailMessage -To $toAddresses -From $fromAddresses -Subject "All over this table" -Body $HTMLBody  -BodyAsHtml -SmtpServer server

Now the table will be the mail.


Couple of things I wanted to point out outside of that

I had an issue with your $a. I removed all of the outer double quotes. Was not reading with them present.

$a = @'
<style>
BODY{background-color:lightgrey;}
TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}
TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}
</style>
'@

While we are talking about $a you use that as your foreach process variable and you CSS variable. Use meaningful names and you wont get stuck with mistakes where you are overwriting your own variables by accident.

You are making the $denied array from the filtered contents of an existing array. While there are not too many items that is a performance hog and not required.

$denied = $result | Where-Object{
  $_.MaintenanceWindow -eq 'Not found!' -or
  $_.LastReboot -eq 'Access Denied!'
}

Upvotes: 2

Related Questions