Home > front end >  Sending an HTML Email through PowerShell
Sending an HTML Email through PowerShell

Time:10-04

I have the following code that is sending an email, but the body element is emailing with all of the HTML formatting such as <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>HTML TABLE</title> </head><body> <h2>Folders older than 30 days</h2> (note that is not the whole email. For the entire email see below)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>HTML TABLE</title> </head><body> <h2>Folders older than 30 days</h2>
<div>
    Folders were removed on - now
    <br></br>
    Location: \\Server01\XFER\Cory
</div>
<br></br> <table> </table> </body></html>

Photo of Email

How do I get the HTML to work?

Here is the code:

$EmailFrom = “[email protected]”

$EmailTo = “[email protected]”

$Subject = “Test”

$body = ConvertTo-Html -PreContent @"
 <h2>Folders older than 30 days </h2>
<div>
    Folders were removed now
    <br> </br>
    Location: here
</div>
 <br> </br>
"@

$SMTPServer = “smtp.outlook.com”

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)

$SMTPClient.EnableSsl = $true

$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("[email protected]", "powershell")

$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body )

CodePudding user response:

The smtpClient method 'send' supports an object of the type mailMessage:

Send(MailMessage)   
Sends the specified message to an SMTP server for delivery.

Link

There you can specify the property IsBodyHmtl.

Link

But as you are on PowerShell you could simply use the cmdlet send-mailmessage there you have the parameter 'BodyAsHtml'.

CodePudding user response:

Try this:

$EmailFrom = “[email protected]”

$EmailTo = “[email protected]”

$Subject = “PowerShell Email”

$body = ConvertTo-Html -PreContent @"
 <h2>Folders older than 30 days </h2>
<div>
    Folders were removed now
    <br> </br>
    Location: here
</div>
 <br> </br>
"@

$EmailMessage = New-Object System.Net.Mail.MailMessage
$EmailMessage.From = $EmailFrom
$EmailMessage.To.Add( $EmailTo)
$EmailMessage.Subject = $Subject
$EmailMessage.IsBodyHtml = $true
$EmailMessage.Body = $body

$SMTPServer = “smtp.outlook.com”

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)

$SMTPClient.EnableSsl = $true

$SMTPClient.Credentials = New-Object          
System.Net.NetworkCredential("[email protected]", "P@ssw0rd")

$SMTPClient.Send($EmailMessage)
  • Related