# Формирование рассылки писем с вложениями # Рекурсивная проверка каталога для отправки вложений различным адресатам (например, для рассылки счетов или иных документов) $path = "D:\FileServer" $pathsys = "D:\Service\Mail" $content = Get-ChildItem $path -Recurse -Filter "$*" | where { ! $_.PSIsContainer -eq $true } $errlog = "$pathsys\error_docs.log" $dt = get-date -f "yyyy.MM.dd" $da = get-date -f "yyyyMMdd" $sign = Get-Content "$pathsys\sign" $Rcpt = "user@mail.ru" $a7z = "C:\Program Files\7-Zip\7z.exe" $pathp = "D:\Service\Temp\docs_$da.7z" Function SendEmail { Param ( [parameter(Mandatory=$true, ValueFromPipeline=$false)] $addr, [parameter(Mandatory=$true, ValueFromPipeline=$false)] [String] $Body, [parameter(Mandatory=$true, ValueFromPipeline=$false)] $matt ) Begin { $smtpserver = smtp.mail.ru $smtpport = 587 $smtp = new-object Net.Mail.SmtpClient $smtpserver, $smtpport $smtp.Enablessl = $true $smtp.Credentials = New-Object System.Net.NetworkCredential("user@mail.ru", "password") $smtp.Timeout = 10000 } Process { $EmailFrom = "Служба уведомлений " $EmailCC = "copy@mail.ru" $Subject = 'Документы от '+$dt $msg = New-Object system.net.mail.mailmessage ForEach ($EmailAddr in $addr) { $msg.To.Add($EmailAddr) } if ($matt) { ForEach($fatt in $matt) { $attach = new-object Net.Mail.Attachment($fatt) $msg.Attachments.Add($attach) } } else { Break } $msg.CC.Add($EmailCC) $msg.DeliveryNotificationOptions = "OnSuccess" $msg.Priority = "high" $msg.From = $EmailFrom $msg.Subject = $Subject $msg.body = $Body $msg.IsBodyHTML = $true $msg.BodyEncoding = [System.Text.Encoding]::UTF8 $smtp.Send($msg) if ($error) { $erdt = get-date -f "yyyy.MM.dd HH:mm:ss" Write-Output $Body | out-file -append -filepath $errlog -Encoding "UTF8" Write-Output "$erdt $error" | out-file -append -filepath $errlog -Encoding "UTF8" } $error.clear() } } # Body $cntDoc = 1 Foreach($file in $content){ $file = ($file -replace "pdf","") $file = ($file -replace "\$","") if ($cntDoc -gt 1) { $DocList = $DocList+"$cntDoc. $file;
" } else { $DocList = "$cntDoc. $file;
" } $cntDoc+=1 } $Body = "Новые сканы документов от $dt

" $Body = $Body+$DocList+$sign # 7zip Foreach($file in $content){ $ad = ($file.FullName -split "\$")[0] $af = ($file.Name -replace "\$","") Rename-Item -Path $file.FullName -NewName $af $nf = $ad+$af & $a7z @('a',$pathp,'-t7z',$nf) } # Send if(Test-Path ($pathp)) { SendEmail $Rcpt $Body $pathp } if ($error) { $erdt = get-date -f "yyyy.MM.dd HH:mm:ss" Write-Output $file | out-file -append -filepath $errlog -Encoding "UTF8" Write-Output "$erdt $error" | out-file -append -filepath $errlog -Encoding "UTF8" } $error.clear()