我正在尝试发送电子邮件,但出现语法错误:
$fromaddress = "[email protected]"
$toaddress = @('[email protected]>', '[email protected]>')
$bccaddress = @('[email protected]')
#$CCaddress = @('[email protected]>')
$Subject = "BAKUP REPORT FOR Instances "
$body = get-content C:\body.txt
$attachment = @("C:\result.text", "C:\result.csv", "C:\object.text", "C:\object.csv")
$smtpserver = "smtp.a.com"
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
#$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
我收到以下错误。
新对象:找不到“附件”和参数计数的重载:“4”。 在第 18 行 char:11 + $attach = new-object Net.Mail.Attachment($attachment) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [New-Object], MethodException +fullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand 异常调用“添加” “1”参数:“值不能为空。 参数名称:项目” 在第19行字符:1 + $message.Attachments.Add($attach) +~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException +FullyQualifiedErrorId:ArgumentNullException 使用“1”参数调用“Send”的异常:“发送邮件失败。” 在第 22 行字符:1 + $smtp.Send($message) + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullQualifiedErrorId : SmtpException
我更喜欢使用Send-MailMessage,因为它的语法更好Net.Mail
,您也可以使用Splatting使其更易于阅读:
$messageParameters = @{
From = "[email protected]"
To = "[email protected]>", "[email protected]>"
Bcc = "[email protected]"
#Cc = "[email protected]>"
Subject = "BAKUP REPORT FOR Instances"
Body = Get-Content C:\body.txt
Attachments = "C:\result.text", "C:\result.csv", "C:\object.text", "C:\object.csv"
SmtpServer = "smtp.a.com"
}
Send-MailMessage @messageParameters -BodyAsHtml
根据您的 SMTP 服务器,您可能还需要为身份验证和/或 SSL 指定凭据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句