New line in body of an email when output is from an array

Andrew Rose 1 Reputation point
2021-11-24T10:17:15.9+00:00

I load some information in from a file which is of the format

User1
User2
etc

using $Input = Get-Content "StaticUsers.txt"

At the end of my script I send an email with the body being sent to a number of users using

$body = "$Input" + "rn"

The issue is that the received email shows the list as the following

User1 User2 etc

instead of each item on a new line. How can I achieve this?

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Limitless Technology 39,921 Reputation points
    2021-11-26T08:40:59.807+00:00

    Hello

    Thank you for your question and reaching out.

    The PowerShell newline indicator is n, and can only be used in double quotes. Single quotes will print the actual "n".

    For Example :
    $body = "first line" + "`n" + "second line"

    Also, One solution would be to use <br /> to break lines and specify the switch -BodyAsHtml so that body would be treated as html and email client would display it correctly, alternatie approach would be to use `n for line breaks and keep body as text.


    --If the reply is helpful, please Upvote and Accept as answer--

    1 person found this answer helpful.

  2. Rich Matheisen 47,901 Reputation points
    2021-11-24T20:01:32.953+00:00

    Use the "-join" operator:

    $Input = 1,2,3,4
    $body = ($input -join [Environment]::NewLine) + [Environment]::NewLine
    

    You can substitute "rn" for "[Environment]::NewLine" if you like.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.