通过Powershell脚本发送电子邮件时出错

时间:2018-04-30 13:39:52

标签: windows powershell windows-10

我正在尝试发送一封包含Powershell脚本的电子邮件,当我运行我的程序时,我收到的错误如下:

Exception setting "Add": "Cannot set the Value property for PSMemberInfo object of type 
"System.Management.Automation.PSMethod"."
At C:\Users\documents\eventSender.ps1:11 char:1
+ $emailMessageObject.To.Add = $toEmailAddress
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

'Attachments' is a ReadOnly property.
At C:\Users\documents\eventSender.ps1:14 char:1
+ $emailMessageObject.Attachments = $currentAttachment
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

Exception calling "Send" with "1" argument(s): "A recipient must be specified."
At C:\Users\documents\eventSender.ps1:18 char:1
+ $smtpClient.Send($emailMessageObject)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException

现在我对powershell相当新,所以我真的不明白错误,我试图发送消息的方式如下:

$todaysDate = Get-Date -DisplayHint Date
$smtpServerAddress = "smtp.google.com"
$toEmailAddress = "admins@me.com"
$fromEmailAddress = "me@me.com"
$subjectMessage = "Files for date -> $todaysDate"
$body = "log files sent on $todaysDate (this is a test)"
$currentAttachment = "C:/Users/Downloads/TBG-1.htm"

$emailMessageObject = New-Object System.Net.Mail.MailMessage
$emailMessageObject.From = $fromEmailAddress
$emailMessageObject.To.Add = $toEmailAddress
$emailMessageObject.Subject = $subjectMessage
$emailMessageObject.Body = $body
$emailMessageObject.Attachments = $currentAttachment

$smtpClient = New-Object Net.Mail.SmtpClient($smtpServerAddress, 587)
$smtpClient.EnableSsl = $true
$smtpClient.Send($emailMessageObject)

我在收到此错误消息的位置错误,我是否需要使用与我的电子邮件地址匹配的凭据才能发送此消息?

2 个答案:

答案 0 :(得分:1)

您应该使用Send-MailMessage代替System.Net.Mail.Message

我发现最简单的方法是通过Splatting:

$Splat = @{ 
    To         =$toEmailAddress  
    Body       =$body
    Subject    =$subjectMessage  
    SmtpServer =$smtpServerAddress  
    From       =$fromEmailAddress
    Attachements = $currentAttachment    
    } 

    Send-MailMessage @Splat 

如果您的交易所要求授权发件人,您只需要指定凭据。如果是这样,您只需将$Splat更改为:

即可
 $Splat = @{ 
    To         =$toEmailAddress  
    Body       =$body
    Subject    =$subjectMessage  
    SmtpServer =$smtpServerAddress  
    From       =$fromEmailAddress
    Attachements = $currentAttachment 
    Crendential = $creds   
    } 

    Send-MailMessage @Splat 

答案 1 :(得分:0)

$emailMessageObject.To.Add($toEmailAddress)是一种方法,因此您必须像MailMessage.Attachments

一样调用它

$emailMessageObject.Attachments.Add($currentAttachment)也是一个集合,因此您必须使用{{1}}

添加项目

Source