Search code examples
htmlemailpowershell-3.0

embedded HTML results in the email body is not as expected


We pull files from a third-party application everyday and send send out an email with all the files copied to the relevant person on the other side. When I generate the html file my results are as expected but when I try to embed the same results as html in the body of my e-mail I just get numbers instead of the folder path & file name. Not sure what's causing this. Please guide me.

$head = @"
<Title>Files in folder</Title>
<style>
Body   { font-family: "Verdana", "Geneva", sans-serif; background-color:#F0E68C; }
table  { border-collapse:collapse; width:50% }
td     { font-size:12pt; border:1px #0000FF solid; padding:5px 5px 5px 5px; }
th     { font-size:14pt; text-align:left; padding-top:5px; padding-bottom:5px; background-color:#0000FF; color:#FFFFFF; }
name tr{ color:#000000; background-color:#0000FF; }
</style>
"@

#file path
$path = "D:\\Temp"
$root = (Get-Item $path).FullName

#output html as string
$html = Get-ChildItem $root -recurse -include *.xlsx, *.docx, *.txt, *.csv | 
        where { $_.PSIsContainer -eq $false } | % 
        {
        $fPath = $_.FullName.Remove(0, $root.Length + 1)
        Write-Output "<a href=`"$fPath`">$fPath</a><br />" 
        } | ConvertTo-Html -Head $head | Out-String

#email
$email = @{
 To = "[email protected]"
 from = "[email protected]"
 BodyAsHtml = $True
 Body = $html
 Subject = "Files in the folder"
 SmtpServer = "mailserver"
}

Send-MailMessage @email

Solution

    1. ConvertTo-Html converts objects into HTML whereas you already produce HTML manually.
      Put it into $body variable and use in -body parameter of ConvertTo-Html.
    2. There's no need for $root, just use $path in Get-ChildItem
    3. PS3.0+ has -File switch in Get-ChildItem to list only the files so where is not needed
    4. It's safer to use -LiteralPath always in order not to fail on paths with [ and ] characters interpreted as a wildcard specifier.
    5. In PowerShell there's no need to escape \ inside strings, just write 'D:\Temp'

    $body = Get-ChildItem -Literal $path -Recurse -File -Include *.xlsx, *.docx, *.txt, *.csv |
            ForEach {
                $fPath = $_.FullName.Substring($path.Length + 1)
                "<a href=""$fPath"">$fPath</a><br>" 
            }
    $html = ConvertTo-Html -Head $head -Body $body | Out-String