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

Faizan Sayed 46 Reputation points
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 "xyz@abg.com" -To test@abc.com -Subject test -BodyAsHtml -Body "User list below $groups1" -SmtpServer smtpgate.net 
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,389 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 30,376 Reputation points Microsoft Vendor
    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 "xyz@abg.com" -To test@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 45,096 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 "xyz@abg.com" -To test@abc.com -Subject test -BodyAsHtml -Body "User list below`r`n$groups" -SmtpServer smtpgate.net 
    
    0 comments No comments

  2. Faizan Sayed 46 Reputation points
    2021-03-23T10:52:34.403+00:00

    Thanks @Ian Xue (Shanghai Wicresoft Co., Ltd.) by adding -join '<br>' its working now

    $groups = (Get-Content $path) -join '<br>'  
    
    0 comments No comments