Powershell脚本无法发送给多个收件人

Geo*_*wdy 5 email powershell smtp

我正在使用powershell脚本来创建磁盘空间的HTML报告并将其作为电子邮件发送.不幸的是,我无法将脚本发送给多个电子邮件收件人.我正在使用的脚本可以在这里找到:

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 = "to1@email.com", "to2@email.com"
sendEmail from@email.mail $recipients "Disk Space Report - $Date" smtp.server $freeSpaceFileName
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

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
Run Code Online (Sandbox Code Playgroud)

小智 7

您使用的MailMessage构造函数只接受一个电子邮件地址.请参阅MSDN文档 http://msdn.microsoft.com/en-us/library/5k0ddab0.aspx

你应该尝试使用,Send-MailMessage因为它的-To参数接受一个地址数组

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

注意:PowerShell v2.0中引入了Send-MailMessage,因此仍然有使用其他命令的示例.如果您需要使用v1.0,那么我将更新我的答案.


ian*_*411 7

使用PowerShell发送电子邮件有两种方法:

  1. 对于该Send-MailMessage方法(在PowerShell版本2中介绍):

    $to = "to1@email.com", "to2@email.com"

  2. 对于System.Net.Mail方法(来自PowerShell版本1):

    $msg.To.Add("to1@email.com")

    $msg.To.Add("to2@email.com")


小智 6

System.Net.Mail也可以在一行中完成此操作。只需确保在单个字符串中添加括号和所有收件人(以逗号分隔):

$msg = New-Object System.Net.Mail.MailMessage("from@email.com","to@email1.com,to@email2.com","Any subject,"Any message body")
Run Code Online (Sandbox Code Playgroud)

这也适用于 RFC-822 格式的电子邮件地址:

System.Net.Mail.MailMessage("Sender <from@email.com>","Rcpt1 <to@email1.com>,Rcpt2 <to@email2.com>","Any subject,"Any message body")
Run Code Online (Sandbox Code Playgroud)