Link to home
Start Free TrialLog in
Avatar of Exchange User
Exchange User

asked on

Unable to send emails with multiple attachments using Send-MailMessage in powershell

Hi all,

I am trying to write a code (dont have a coding background but reading stuff and trying to write it up) in which the code will check all the subfolders for pdf files inside one main folder and then for each folder, it will send those files to their respective customers. Every folder has a separate customer. I was able to make it work for 2 customers but with only 1 attachment, if I add a 2nd attachment for customer B, it fails with error "SendMailMessage: The given path's format is not supported". Customer A works fine though. Can any of you guys please point me in the right direction ?

Thanks

Clear-Host
$SMTPServer = "mail.abc.com"
$From = "admin@abc.com"
$folder = Get-ChildItem "E:\Attachments\" -Recurse -Directory
$file_attachments = @()
foreach ($subfolder in $folder)
{
if ($subfolder.Name -eq "Customer A")
{
$custa = Get-ChildItem "E:\Attachments\Customer A\"
$custa | foreach {$file_attachments += $_.FullName}
Write-Host "Folder Customer A is Present"
Send-MailMessage -From $From -to customerA@xyz.com -SmtpServer $SMTPServer -Attachments $file_attachments -Subject "Sending File A"
}
if ($subfolder.Name -eq "Customer B")
{
Clear-Variable -name file_attachments
Write-Host "Folder Customer B is Present"
$custb = Get-ChildItem "E:\Attachments\Customer B\"
$custb | foreach {$file_attachments += $_.FullName}
Send-MailMessage -From $From -to customerB@domain.com -SmtpServer $SMTPServer -Attachments $file_attachments -Subject "Sending invoice B"
}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Shaun Vermaak
Shaun Vermaak
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Exchange User
Exchange User

ASKER

It is WORKING !! What did I do wrong ? And is it flexible to add more files in those folders ?

Thanks :)
And, is there any way I can automate the process in which I have to type all customer folder names and their email addresses in the code and instead I can pull this info from a csv file maybe ? I think that will be easier and the code will be a bit smaller ?
You should be able to add more files. You had multiple parsing from one object array to another and I made it so that each mail command uses its own attachment object array
You are the BEST ! Thank you. Happy New Year !

Regards