Home > OS >  Create attachment array for sending email
Create attachment array for sending email

Time:12-15

I have to send email and attach files which are having more than 4 lines as content.

$Final_File_list = Get-ChildItem -Path "E:\files" -Filter "New_*.txt"

foreach($NewFile in $Final_File_list)
{
    $Full_File_Path = $NewFile.FullName
    $GetLines = (Get-Content -Path $Full_File_Path | Measure-Object -Line).Lines

    if($GetLines -gt 4)
    {
        [array]$rn_all =$Full_File_Path "," #$Full_File_Path -join ','
    }
}

Please let me know how add multiple files as attachment in this case.

CodePudding user response:

I think you were very close already.

Try

$Final_File_list = Get-ChildItem -Path "E:\files" -Filter "New_*.txt"

$attachments = foreach($NewFile in $Final_File_list) {
    if (@(Get-Content -Path $NewFile.FullName).Count -gt 4) {
        # simply output the FullName so it gets collected in variable $attachments
        $NewFile.FullName
    }
}

if ($attachments) {
    # send your email
    $mailParams = @{
        From        = '[email protected]'
        To          = '[email protected]'
        Subject     = 'PortErrors'
        Body        = 'Please see the attached files'
        SmtpServer  = 'smtp.yourcompany.com'
        Attachments = $attachments
        # more parameters go here
    }
    # send the email
    Send-MailMessage @mailParams
}

P.S. If the files can be large, you can speed up a little if you add parameter -TotalCount to the Get-Content line, so it stops when it reads more than 4 lines max:

if (@(Get-Content -Path $NewFile.FullName -TotalCount 5).Count -gt 4) {
...
}
  • Related