Konzy262
Konzy262

Reputation: 3087

Single line break in body of powershell MailMessage not working

For some reason when attempting to populate the body of an email in powershell, a single line break using the `n escape sequence is not working, however a double is.

This is my code...

param([string]$BuildId, [string]$BuildName)

$EmailTo = "[email]"
$EmailFrom = "[email protected]"
$Subject = "$BuildName $BuildId SpecFlow Reports" 
$Body = "The following SpecFlow reports are attached: `n`n" 
$SMTPServer = "smtp.sendgrid.net"

$date = Get-Date -Format yyyy-MM-dd

$files = Get-ChildItem "C:\Build\SA.SEPA.Web.UI.Selenium" -Recurse | Where-Object { $_.Name -match "^.*$date.*\.html$" } | % { $_.FullName }

foreach($item in $files)
{
    $Body += "$item `n"
}

$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)

foreach($item in $files)
{
    $attachment = New-Object System.Net.Mail.Attachment($item)
    $SMTPMessage.Attachments.Add($attachment)
}

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("apikey", "[apiKey]"); 
$SMTPClient.Send($SMTPMessage)

This is the section that is failing to add a line break

foreach($item in $files)
{
    $Body += "$item `n"
}

My email in outlook looks like the following....

enter image description here

You can see that the `n `n double line break has been applied but not the `n. Incidentally if I change to...

foreach($item in $files)
{
    $Body += "$item `n`n"
}  

I do see a double line break.

How do I get just a single line break?

Upvotes: 0

Views: 2015

Answers (2)

andr3yk
andr3yk

Reputation: 176

If you OK to use HTML body you can use <br> for line breaks. You will need to set following property on your message variable:

$SMTPMessage.IsBodyHTML = $true

$Body += "$item <br>"

Upvotes: 0

user3012708
user3012708

Reputation: 946

Just go with [Environment]::NewLine to resolve this one. It will take away most headaches relating to this issue.

Usage:

foreach($item in $files)
{
    $Body += "$item " + [Environment]::NewLine
}

Upvotes: 2

Related Questions