PowerShell代码将每个子文件夹中的文件作为电子邮件附件发送

时间:2019-07-16 11:03:31

标签: powershell

我正在尝试编写一个PowerShell脚本,该脚本将作为附件通过电子邮件发送,并将C:\ Reports \的每个子文件夹中的所有文件一起发送。例如,如果子文件夹是具有a.txt,b.xml和c.jpg的C:\ Reports \ ABC和具有d.txt,e.xml和f.pdf的C:\ Reports \ DEF,则代码应通过电子邮件发送给一封电子邮件中包含.txt,b.xml和c.jpg,另一封电子邮件中包含d.txt,e.xml和f.pdf。

#Connection Details
$username = ”vallabhherlekar@gmail.com”
$password = ”Appya1979!”
$smtpServer = “smtp.gmail.com”

$Directory = Get-ChildItem “C:\Reports\” -Directory
foreach ($d in $Directory) {
    $msg = New-Object Net.Mail.MailMessage
    $smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
    #Uncomment Next line for SSL  
    $smtp.EnableSsl = $true

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

    $msg.From = "vallabhherlekar@gmail.com"
    $msg.To.Add(“vallabhherlekar@gmail.com”)
    $msg.Body=”Please See Attached Files”
    $msg.Subject = “Email with Multiple Attachments”

    Write-Host "Working on directory $($d.FullName)..."
    $files = Get-ChildItem -Path "$($d.FullName)" -File
    foreach ($file in $files) {
        Write-Host “Attaching File :- ” $file.FullName
        $attachment = New-Object System.Net.Mail.Attachment –ArgumentList 
$file.FullName
        $msg.Attachments.Add($attachment)
    }
    $smtp.Send($msg)
    $attachment.Dispose();
    $msg.Dispose();
}

0 个答案:

没有答案