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: https://developers.google.com/gmail/design/css. Below is a sample script to demonstrate this practice:

# Email relay parameters
$emailFrom='admin@kimconnect.com'
$emailTo='hooli@gmail.com'
$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 *