How to send email

Copper Contributor

Hi All,

 

I am new to PS and i need a email message where it sends me by identifying recent file names with date and time in particular folder on the server

below is the simple commands i set in the script where i get empty body message

 

$email = Get-ChildItem -path D:\TFTP-Root | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)}

 

Send-MailMessage -To 'bhuvankumar@gmail.com' -SmtpServer  'smtp.com' -Subject 'Test Email' -Body $email -From tets01@ymail.com

 

Below output i need to get in email body message 

    Directory: D:\TFTP-Root

 

Mode                LastWriteTime         Length Name

----                -------------         ------ ----

-a----        5/11/2020   9:43 PM         226632 testa03-cfg.2020-05-11-22.00.12

-a----        5/11/2020   9:44 PM         227116 testa04-cfg.2020-05-11-22.00.14

 

Thanks,

Bhuvan

2 Replies

@kdvbhuvankumar Almost there my friend! Check the script below. I hope it helps you take the next step!

 

Grtz, Manfred de Laat

# Get the Files
$items = Get-ChildItem -path D:\TFTP-Root | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)}
 
# Create a mailbody
$mailbody = "" 
foreach($item in $items){
    $mailbody += $mailbody + "File: " + $item.FullName + "`n" + "Size (KB): " + $item.Length + "`r`n`n"
}

# Add the mailbody 
Send-MailMessage -To 'xxxxx@gmail.com' -SmtpServer  'smtp.com' -Subject 'Files and Sizes' -Body $mailbody -From "yyyyy@gmail.com"

 

@kdvbhuvankumar 

You cannot send an object as mail body, you need to convert to   string    [[-Body] <string>]

$emailObject = Get-ChildItem -path D:\TFTP-Root | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)}

$emailcsvtxt= $emailObject |select Mode ,LastWriteTime ,Length ,Name|ConvertTo-Csv