Reputation: 3087
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....
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
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
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