Converting Body to HTML Not Working

548 Views Asked by At

I am trying to make my body of text convert to HTML so it does not show as plain text in my email.

Here is the code

$From = ""
$To = ""
$SMTPServer = ""
$SMTPPort = "587"
$Username = ""
$Password = ""
$subject = "Test Powershell"
$body = $htmlreport
$bodyAsHtml = $true
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.Send($From, $To, $subject, $body);

I cant see to get the report to send as HTML.

2

There are 2 best solutions below

0
On BEST ANSWER

Instead of passing the individual strings to $smtp.Send(), you should create a MailMessage object and send that instead:

$msg            = New-Object System.Net.Mail.MailMessage
$msg.From       = $From
$msg.To         = $To
$msg.Subject    = $subject
$msg.Body       = $body
$msg.IsBodyHtml = $true # this is where the magic happens

$smtp             = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
$smtp.EnableSSL   = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)

$smtp.Send($msg) # and then send the message we just composed above
1
On

$bodyAs contains `enter code here`. You should remove that. You also don't set it anywhere.

Maybe try the Send-MailMessage cmdlet instead:

Send-MailMessage -SmtpServer $SMTPServer -To $To -From $From -Subject $subject -Body $body -BodyAsHtml