Send result of ls command using System.Web.Mail.MailMessage


Im trying to write a script to send the result of variable ($content) as the body :

$content = ls -Path $folder | Sort-Object LastWriteTime -Descending

I use [System.Web.Mail.SmtpMail]::Send($mail) to send messages

It works except, i get only the filenames on the same line, i wish to get the same layout (with the columns…)

$mail = New-Object System.Web.Mail.MailMessage
$mail.Fields.Add(“”, $server)
$mail.Fields.Add(“”, $serverPort)
$mail.Fields.Add(“”, $true)
$mail.Fields.Add(“”, $credentials.UserName)
$mail.Fields.Add(“”, $credentials.Password)
$mail.Fields.Add(“”, $timeout / 1000)
$mail.Fields.Add(“”, 2)
$mail.Fields.Add(“”, 1)
$mail.From = $from
$mail.To = $to
$mail.Subject = $subject
$mail.Body = $content

Perhaps i need to change the type of $mail.Body ?


I get :

$mail.Body => name : String , BaseType : System.Object
$content => name : Object[] , BaseType : System.Array

Any idea ?


Thank you so much guys!

If it is a single object returned, then you will see the exact type name, whereas if there are multiple objects returned then the type will be array irrespective of any type.

(ls .\report.csv).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    FileInfo                                 System.IO.FileSystemInfo


IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

If you are writing a PowerShell script then you can use Send-MailMessage CmdLet, and you need to format the content in the body as per your requirement.

Thank you.

As you’ve seen, the mail body needs to be text. Plain text is just that, plain, no colors, formatting, tables, headers. To answer your question, to convert to a string you can use Out-String, an example:

ls *.exe | Select Name, FullName | Out-String | Out-File -FilePath C:\Scripts\ls.txt

to use in email:

$mail.Body = ($content | Out-String)

To get full flexibility in formatting, you should use HTML. This can be as simple as:

$mail.IsBodyHtml = true;
$mail.Body = ($content | ConvertTo-HTML | Out-String)

If you use HTML, you can format it any that you want. Take a look at the free resources on HTML reporting. As Kiran also stated, you can also use Send-MailMessage rather than manually creating the message.