通过comObject Outlook.Application使用多个附件

时间:2015-06-09 20:32:58

标签: email powershell

我有一个进入SCSM的脚本,从IR获取相关文件并将其正确下载到用户的计算机上。 接下来,我需要脚本从客户端的Outlook应用程序创建一封电子邮件,然后在发送电子邮件之前将其显示在屏幕上。

以下是执行该操作的脚本部分:

$GetFiles = Get-ChildItem "$ArchiveRootPath\$IRID\" 

$ol = New-Object -comObject Outlook.Application #| New-Object Net.Mail.MailMessage

$mail = $ol.CreateItem(0)
$mail.To = "johndoe@contoso.com"
$mail.Subject = "This is a test [$IRID]"

Foreach($GetFile in $GetFiles)
{
Write-Host “Attaching File :- ” $GetFile
 $attachment = New-Object System.Net.Mail.Attachment –ArgumentList C:\Temp\SCSM_Archive\$IRID\$GetFile
 $mail.Attachments.Add($attachment)
 }

$inspector = $mail.GetInspector
$inspector.Display()

但是,当我运行脚本时,我收到此错误:

Attaching File :-  email.eml
Exception calling "Add" with "1" argument(s): "Value does not fall within the expected range."
At C:\Temp\SSWireless Script.ps1:99 char:2
+  $mail.Attachments.Add($attachment)
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

从下载文件的脚本的前一部分检查所有变量。 PS能够看到文件,但无法将它们附加到电子邮件中。 我不想使用发送消息功能,因为我们将转移到跨域电子邮件帐户,而宁愿使用outlook来创建电子邮件本身。

1 个答案:

答案 0 :(得分:0)

以下是Microsoft.Office.Interop.Outlook Attachments.Add method 的参考资料。这确认了第一个参数(以及您的案例中唯一的参数)需要是文件的完整路径。

没有必要将[System.Net.Mail.Attachment] .NET对象传递给COM接口。

您的代码应如下所示:

$GetFiles = Get-ChildItem "$ArchiveRootPath\$IRID\" 

$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$mail.To = "johndoe@contoso.com"
$mail.Subject = "This is a test [$IRID]"

Foreach($GetFile in $GetFiles)
{
    Write-Host “Attaching File :- $GetFile.Name"
    $mail.Attachments.Add($GetFile.FullName)
}