Passing the content of txt file to body of Send-MailMessage in powershell

Anonymous
2021-03-22T17:35:59.823+00:00

I want to Pass the content of txt file to body of Send-MailMessage in powershell I tried using the out-sting function and also use FT combination but its giving output in single line over email body I have to print the list of users one below other same as in text file but its getting printer in one line on email body

 $path = "H:\userlist.txt" 
$groups = Get-Content $path 
$groups1 = $groups|format-table|out-string 
Send-MailMessage -From "******@abg.com" -To ******@abc.com -Subject test -BodyAsHtml -Body "User list below $groups1" -SmtpServer smtpgate.net 
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-03-23T06:25:31.597+00:00

    Hi,

    You can add the <br> tags to insert line breaks since you use the "-BodyAsHtml" parameter.

    $path = "H:\userlist.txt"   
    $groups = (Get-Content $path) -join '<br>'  
    Send-MailMessage -From "******@abg.com" -To ******@abc.com -Subject test -BodyAsHtml -Body "User list below $groups1" -SmtpServer smtpgate.net   
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2021-03-22T18:51:38.597+00:00

    The -Body parameter expects a string as its argument. To get the contents of your file as a single string, add the -Raw switch to the Get-Content. The result will contain all the CrLf line-endings, so you'll see pretty much what you see if you opened the file in NotePad.

    Give this a try:

    $path = "H:\userlist.txt" 
    $groups = Get-Content $path -Raw
    Send-MailMessage -From "******@abg.com" -To ******@abc.com -Subject test -BodyAsHtml -Body "User list below`r`n$groups" -SmtpServer smtpgate.net 
    
    0 comments No comments

  2. Anonymous
    2021-03-23T10:52:34.403+00:00

    Thanks @Anonymous by adding -join '<br>' its working now

    $groups = (Get-Content $path) -join '<br>'  
    
    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.