2017-02-10 172 views
2

我想向電子郵件添加多個附件。 有了一個沒有問題,但如果你想添加兩個或更多的不順心的事Powershell - Outlook - 將多個附件添加到電子郵件

我的代碼

$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 

我的文件

名稱:展望
電子郵件:電子郵件@免得。 pl; [email protected]; [email protected]
主題:你很棒
附件:「C:\ outlook \ attachment \ sell.txt」;「C:\ outlook \ attachment \ out.txt 「

錯誤:

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

回答

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()方法,該數組元素在塊內由$_表示。