我正在使用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
我收到以下错误
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
答案 0 :(得分: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,那么我将更新我的答案。
答案 1 :(得分:5)
使用PowerShell发送电子邮件有两种方法:
对于 Send-MailMessage
方法(在PowerShell版本2中介绍):
$to = "to1@email.com", "to2@email.com"
对于 System.Net.Mail
方法(来自PowerShell版本1):
$msg.To.Add("to1@email.com")
$msg.To.Add("to2@email.com")
答案 2 :(得分:1)
使用System.Net.Mail
,您还可以一行完成此操作。只需确保在单个字符串中添加括号和所有用逗号分隔的收件人:
$msg = New-Object System.Net.Mail.MailMessage("from@email.com","to@email1.com,to@email2.com","Any subject,"Any message body")
这也适用于RFC-822格式的电子邮件地址:
System.Net.Mail.MailMessage("Sender <from@email.com>","Rcpt1 <to@email1.com>,Rcpt2 <to@email2.com>","Any subject,"Any message body")
答案 3 :(得分: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 from@email.mail -to $recipients -smtphost smtp.server -subject "Disk Space Report - $Date" -htmlFileName $freeSpaceFileName
答案 4 :(得分:0)
我建议在powershell中使用send-mailmessage,而不是定义自己的函数。我的猜测是你的一个参数类型不匹配。