Powershell - Outlook - 向电子邮件添加多个附件

时间:2017-02-10 13:32:07

标签: powershell email outlook attachment

我想在电子邮件中添加多个附件。 有一个没问题,但如果你试图添加两个或更多的东西出错

我的代码

$file_patch=Get-ChildItem 'C:\OUTLOOK' | Sort {$_.LastWriteTime} | select -last 1 | % { $_.FullName }
$name=Select-String -Path $file_patch -pattern name
$email=Select-String -Path $file_patch -pattern email
$subject=Select-String -Path $file_patch -pattern subject
$attachment=Select-String -Path $file_patch -pattern attachment
$Signature = Get-Content ($env:USERPROFILE + "\AppData\Roaming\Microsoft\Signatures\*.htm")
$rname = $name -replace ".*:"
$remail = $email -replace ".*:"
$rsubject = $subject -replace ".*:"
$rattachment = $attachment -replace ".*attachment:"
$sname = $rname -split ";"
$semail = $remail -split ";"
$ssubject = $rsubject -split ";"
$sattachment = $rattachment -split ";"
$body=Get-Content C:\OUTLOOK\BODY\$sname.txt
$Signature = Get-Content ($env:USERPROFILE + "\AppData\Roaming\Microsoft\Signatures\*.htm")
$sRecipientAddr = $semail
$sMsgSubject = $ssubject
$oOutlook = New-Object -ComObject Outlook.Application 
$oMapiNs = $oOutlook.GetNameSpace("MAPI")
$oMailMsg = $oOutlook.CreateItem(0)
$oMailMsg.GetInspector.Activate()
$sSignature = $oMailMsg.HTMLBody
[Void]$oMailMsg.Recipients.Add($sRecipientAddr)
$oMailMsg.Attachments.Add($sattachment)
$oMailMsg.Subject = $sMsgSubject
$oMailMsg.HTMLBody = $body + $sSignature

我的档案

名:展望
电子邮件:e-mail@lest.pl; boss@company.com; random.dude@email.com
主题:你很棒 附件:" C:\前景\附件\ sell.txt&#34 ;;" C:\前景\附件\ out.txt"

错误:

PS > Value does not fall within the expected range.
+ $oMailMsg.Attachments.Add($sattachment)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], A
+ FullyQualifiedErrorId : System.ArgumentException

可能出现什么问题

1 个答案:

答案 0 :(得分:2)

您正在尝试将数组直接传递到.attachments.add()page here具有Add方法的用法。

因此,我认为如果您以稍微不同的方式添加附件,您应该成功:

...
$sSignature = $oMailMsg.HTMLBody
[Void]$oMailMsg.Recipients.Add($sRecipientAddr)
$sattachment | ForEach-Object { $oMailMsg.Attachments.Add($_) }
$oMailMsg.Subject = $sMsgSubject
$oMailMsg.HTMLBody = $body + $sSignature

假设$sattachment = $rattachment -split ";"确实返回了一个字符串数组,您可以使用ForEach-Object cmdlet循环它。然后将为每个数组元素调用.Add()方法,该方法由块中的$_表示。

相关问题