CreedC
CreedC

Reputation: 69

Sending -replace HTML email

I am trying to use MailMessage object to send an email with PowerShell . The script uses Import-CSV to consume a file, then uses ConvertTo-HTML in the body of the email. I have added some replaced HTML, since the email client I am sending to ignores <style> tags.

Here is my script:

$smtpServer = "x.x.x.x"
$smtpFrom = "[email protected]"
$smtpTo = "[email protected]"
$messageSubject = "Weekly Student Device Repair Summary $((Get-Date).ToShortDateString())"

$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $true

$summ = Import-Csv -Path 'C:\folder\file.csv'

$message.body = @"
<html>
    <body>
    Hello,<br><br>
    Here is your weekly repair summary.<br><br>
        $($summ | ConvertTo-Html)<br><br>
    Thank you,<br><br>
    Technology
    </body>
<html>
"@

$finalHTML = $message.body -replace "<table", "<table border='0' cellspacing='0' cellpadding='10' style='border: 1px solid black; border-collapse: collapse;'"
$finalHTML = $finalHTML -replace "<th", "<th border='0' cellspacing='0' cellpadding='0' style='border: 1px solid black; border-collapse: collapse; padding:5px;'"
$finalHTML = $finalHTML -replace "<td", "<td border='0' cellspacing='0' cellpadding='0' style='border: 1px solid black; border-collapse: collapse; padding:5px;'"

$finalHTML | Out-File "c:\folder\file.html"

$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($finalHTML)

I am confused because the | Out-File works and looks exactly how I want the email body to look.

The $smtp.Send($finalHTML) errors out though, with:

"Cannot find an overload for "Send" and the argument count: '1'".

If I replace $smpt.Send($finalHTML) with $smpt.Send($message), the script runs, the email sends, it is HTML, but none of the $finalHTML is applied.

Upvotes: 2

Views: 653

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

Its because the Send method takes a System.Net.Mail.MailMessage object as parameter so you probably want to assign the $finalHTML to $message.body and pass the message:

# ....
$message.body = $finalHTML
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)

Upvotes: 1

Related Questions