【问题标题】:Powershell for Automation of sending mails via a pathPowershell 用于通过路径自动发送邮件
【发布时间】:2020-07-30 06:52:38
【问题描述】:

我想通过使用 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()
}

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

请帮帮我。

【问题讨论】:

  • 如果你想为每个附件发送单独的邮件,你应该每次都创建一个 new 带有属性的邮件项。但是,为什么要通过 Outlook 发送呢?
  • 为什么选择 Outlook?只需使用Send-MailMessage
  • 可能你应该-filterGet-ChildItem的项目多一点,只包括-files

标签: powershell automation email-attachments


【解决方案1】:

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

此外,您使用 (IMO) 混淆变量名..

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

所以如果你不介意我已经改变了下面的变量名更有意义。

另外,Get-ChildItem 可以同时返回 DirectoryInfoFileInfo 对象。由于您只需要文件,因此请使用-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()

【讨论】:

  • 谢谢伙计。它帮助了我。我没有生成新邮件
猜你喜欢
  • 2012-07-08
  • 2016-04-30
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
相关资源
最近更新 更多