Posted On January 14, 2021

How To Format HTML Content For Email

kimconnect 0 comments
blog.KimConnect.com >> Codes >> How To Format HTML Content For Email

Major email service providers such as Google Gmail and Microsoft Office 365 have been supporting HTML formatting using CSS to a limited extent. In the case of Gmail, this documentation is given to developers: . Below is a sample script to demonstrate this practice:

# Email relay parameters
$emailFrom='[email protected]'
$emailTo='[email protected]'
$subject='Some Test Reports'
$smtpRelayServer='smtp.gmail.com'

# CSV Reporting contents
$reportFile='C:\scripts\logs\someTestReport.csv'

    $css=@"
    <style>
    .h1 {
        font-size: 18px;
        height: 40px;
        padding-top: 80px;
        margin: auto;
        text-align: center;
    }
    .h5 {
        font-size: 22px;
        text-align: center;
    }
    .th {text-align: center;}
    .table {
        padding:7px;
        border:#4e95f4 1px solid;
        background-color: white;
        margin-left: auto;
        margin-right: auto;
        width: 100%
        }
    .colgroup {}
    .th { background: #0046c3; color: #fff; padding: 5px 10px; }
    .td { font-size: 11px; padding: 5px 20px; color: #000;
          width: 1px;
          white-space: pre;
        }
    .tr { background: #b8d1f3;}
    .tr:nth-child(even) {
        background: #dae5f4;
        width: 1%;
        white-space: nowrap
    }
    .tr:nth-child(odd) {
        background: #b8d1f3;
        width: 1%;
        white-space: nowrap
    }
    </style>
"@

$reportContent=Import-CSV $reportFile | ConvertTo-Html -fragment | Out-String
$reportHtml=$reportContent -replace '\<(?<item>\w+)\>', '<${item} class=''${item}''>'
$emailContent='<html><head>'+$css+"<h5 class='h5'>Test Report</h5>"+$reportHtml+'</body></html>'

    Send-MailMessage -From $emailFrom `
    -To $emailTo `
    -Subject $subject `
    -Body $emailContent `
    -BodyAsHtml `
    -SmtpServer $smtpRelayServer

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Add Local User as an Administrator on All Servers in Domain

# addLocalAccountOnAllServers.ps1 # Feature: using only legacy commands for maximum compatibility # Set variables $newUsername='backupAdmin'…

PowerShell: Detect Whether Computer is Connected To Domain

# The easy method $domainConnected=.{ try { [void]::([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()) return $true } catch{ return $false }…

PowerShell: Get Failed Scheduled Tasks on a Windows Machine

The following function will query the local Windows Tasks Scheduler for custom schedules and output…