I'm trying to write a PowerShell script that would email, as attachments, all files in each subfolder of C:\Reports\ together in an email. For instance, if the subfolders are C:\Reports\ABC having a.txt, b.xml and c.jpg and C:\Reports\DEF having d.txt, e.xml and f.pdf, the code should email a.txt, b.xml and c.jpg in one email and d.txt, e.xml and f.pdf in another. I wrote the below code:-

$Directory=Get-ChildItem "C:\Reports\" -Directory 
$Cred = Get-Credential 
Foreach($d in $Directory) { 
Write-Host "Working on directory $($d.FullName)..." 
$files=Get-ChildItem -Path "$($d.FullName)"
cd $d.Fullname  
Send-MailMessage -From "vallabhherlekar@gmail.com" -To "vallabhherlekar@gmail.com" -Subject "test" -SmtpServer "smtp.gmail.com" -Port "587" -Attachments $files -BodyAsHtml "test msg" -Credential $Cred -UseSsl

However this seems to attaching only the last file in each subfolder, then moving on to the next folder and email. I wonder how Get-ChildItem - File can be properly used with Send-MailMessage - Attachments to achieve what I'm trying to do.


Here is some (untested) code:

#Connection Details
$smtpServer = "mail.server.local"
$msg = new-object Net.Mail.MailMessage

#Change port number for SSL to 587
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 

#Uncomment Next line for SSL  
#$smtp.EnableSsl = $true

$smtp.Credentials = New-Object System.Net.NetworkCredential( $username, $password )

#From Address
$msg.From = "john@gmail.com"
#To Address, Copy the below line for multiple recipients

#Message Body
$msg.Body="Please See Attached Files"

#Message Subject
$msg.Subject = "Email with Multiple Attachments"

#your file location
$files=Get-ChildItem "C:\Reports\"

Foreach($file in $files)
Write-Host "Attaching File :- " $file
$attachment = new-object Net.Mail.Attachment -ArgumentList $file.FullName



  • My Bad. My code works. I had some files having size 0 bytes. Only those weren't getting sent. Another thing I want to do is that once the sub-directory's contents have been emailed I need to delete it and all the files it contains within the loop. Would someone be able to help me with that? – Vallabh Herlekar Jul 19 at 18:08
  • That's another question, but just add another Foreach($file in $files) loop to do that. – harrymc Jul 19 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.