2013-03-06 14 views
4

我正在使用PowerShell腳本,它將創建一個磁盤空間的HTML報告並將其作爲電子郵件發送。不幸的是,我無法將腳本發送給多個電子郵件收件人。我使用該腳本可以在這裏找到:Powershell腳本無法發送給多個收件人

http://gallery.technet.microsoft.com/scriptcenter/6e935887-6b30-4654-b977-6f5d289f3a63

下面是腳本中的相關部分...

$freeSpaceFileName = "FreeSpace.htm" 
$serverlist = "C:\sl.txt" 
$warning = 90 
$critical = 75 
New-Item -ItemType file $freeSpaceFileName -Force 

Function sendEmail 
{ param($from,$to,$subject,$smtphost,$htmlFileName) 
$body = Get-Content $htmlFileName 
$smtp= New-Object System.Net.Mail.SmtpClient $smtphost 
$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body 
$msg.isBodyhtml = $true 
$smtp.send($msg) 
} 

$date = (get-date).ToString('yyyy/MM/dd') 
$recipients = "[email protected]", "[email protected]" 
sendEmail [email protected] $recipients "Disk Space Report - $Date" smtp.server $freeSpaceFileName 

我收到以下錯誤

New-Object : Exception calling ".ctor" with "4" argument(s): "The specified string is not in the form required for an e 
-mail address." 
At E:\TRIRIGA\dps_jobs\DiskSpaceReport.ps1:129 char:18 
+ $msg = New-Object <<<< System.Net.Mail.MailMessage $from, $to, $subject, $body 
+ CategoryInfo   : InvalidOperation: (:) [New-Object], MethodInvocationException 
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand 

回答

7

您正在使用的MailMessage構造函數只需要一個電子郵件地址。請參閱MSDN文檔 http://msdn.microsoft.com/en-us/library/5k0ddab0.aspx

你應該嘗試使用Send-MailMessage,而不是因爲它是-To參數接受地址數組

Send-MailMessage -from [email protected] -To $recipients -Subject "Disk Space Report - $Date" -smptServer smtp.server -Attachments $freeSpaceFileName

注:發送-MAILMESSAGE使用PowerShell 2.0版引入所以這就是爲什麼有仍然是使用其他命令的示例。如果你需要使用v1.0,那麼我會更新我的答案。

0

試試這個:

Function sendEmail 
{ param($from,[string[]]$to,$subject,$smtphost,$htmlFileName) 
$body = Get-Content $htmlFileName 
$smtp= New-Object System.Net.Mail.SmtpClient $smtphost 
$msg = New-Object System.Net.Mail.MailMessage 
$msg.from =$from 

foreach($a in $to) 
{ 
    $msg.to.Add($a) 
} 

$msg.Subject= $subject 
$msg.Body = $body 
$msg.isBodyhtml = $true 
$smtp.send($msg) 
} 

sendemail -from [email protected] -to $recipients -smtphost smtp.server -subject "Disk Space Report - $Date" -htmlFileName $freeSpaceFileName 
+0

我試過兩個不同的電子郵件地址。當我設置$收件人只是其中一個地址它的作品。但是,一旦我將它們都結合在$收件人列表中,它就會失敗。 – 2013-03-06 20:51:46

+0

@GeoffDawdy,是的..我發佈了一個新的解決方案!在PowerShell v3.0上,我沒有錯誤,但發送給第二個收件人的電子郵件從未發送過。這樣$ msg.to被填充。 – 2013-03-06 21:10:40

0

我建議在powershell中使用send-mailmessage,而不是定義自己的函數。我的猜測是你的某個參數的類型不匹配。

相關問題