用于通过路径自动发送邮件的 Powershell

Powershell for Automation of sending mails via a path

我想使用 Powershell 自动执行通过 outlook 发送邮件的过程,如果路径提供的特定文件夹中有很多文件,它应该从该文件夹中获取每个文件作为附件到邮件。 意味着应该为该路径中的每个文件发送单独的邮件

$OL = New-Object -ComObject outlook.application

Start-Sleep 5

<#
olAppointmentItem
olContactItem
olDistributionListItem
olJournalItem
olMailItem
olNoteItem
olPostItem
olTaskItem
#>

#Create Item
$mItem = $OL.CreateItem("olMailItem")

$mItem.To = "PlayingWithPowershell@gmail.com"
$mItem.Subject = "PowerMail"
$mItem.Body = "SENT FROM POWERSHELL"
$file = "C:\Users\Desktop\Xyz"
foreach($files in Get-ChildItem $file)
{
 $mItem.Attachments.Add($files)
 $mItem.Send()
}

像这样尝试但显示错误,如“找不到成员,无法调用空值表达式,项目已被移动或删除”

请帮帮我。

如评论所述,如果您想为文件夹中的每个文件发送一封新电子邮件,您应该在循环中创建一个新邮件项目并发送它。

此外,您使用 (IMO) 令人困惑的变量名称..

  • 您调用的文件的路径$file
  • 您调用的循环中使用的单个文件项$files

如果您不介意的话,我已经更改了下面的内容,使变量名称更有意义。

此外,Get-ChildItem 可以 return 两个 DirectoryInfo and FileInfo 对象。由于您只需要文件,请使用 -File 开关。

$path = "C:\Users\Desktop\Xyz"

$OL = New-Object -ComObject outlook.application

foreach($file in (Get-ChildItem -Path $path -File)) {
    # create a new mail item object for each file to attach
    $mItem = $OL.CreateItem("olMailItem")

    $mItem.To      = "PlayingWithPowershell@gmail.com"
    $mItem.Subject = "PowerMail"
    $mItem.Body    = "SENT FROM POWERSHELL"
    # Outlook wants the full path and file name, not a FileInfo object
    $mItem.Attachments.Add($file.FullName)
    $mItem.Send()
}

$OL.Quit()
# clean-up used COM object
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($OL)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()