无法发送powershell电子邮件 - 您无法在空值表达式上调用方法

时间:2015-08-28 16:42:18

标签: powershell

我在本地计算机上运行了这个,但是当我在另一台计算机上尝试它时,它在同一个地方有相同的文件等,它会因此错误而失败。

function email 
{
  $emailSmtpServer = "smtp-mail.outlook.com"
  $emailSmtpServerPort = "587"
  $emailSmtpUser = "USERNAME"
  $emailSmtpPass = "PASSWORD"
  $attachment = "C:\BackupLog.log"
  $emailMessage.Attachments.Add($attachment)
  $emailMessage = New-Object System.Net.Mail.MailMessage
  $emailMessage.From = "myemail@hotmail.co.uk"
  $emailMessage.To.Add( "myemail@civil.lmco.com" )
  $emailMessage.Subject = "Database Issues"
  $emailMessage.IsBodyHtml = $true
  $emailMessage.Body = "Test"

  $SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer ,$emailSmtpServerPort )
  $SMTPClient.EnableSsl = $true
  $SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );

  $SMTPClient.Send( $emailMessage )
}

这是输出

PS C:\Users\XXLOCKRG1> email
You cannot call a method on a null-valued expression
At C:\database_backups\powershell scripts\functions\email.ps1:8 char:34
+ $emailMessage.Attachments.Add <<<< ($attachment)
+ CategoryInfo          : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

2 个答案:

答案 0 :(得分:2)

您有两行错误的代码:

$emailMessage.Attachments.Add($attachment) # $emailMessage isn't instantiated yet
$emailMessage = New-Object System.Net.Mail.MailMessage

应该是:

$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.Attachments.Add($attachment)

您需要在引用其成员之前实例化您的对象。

答案 1 :(得分:2)

您在尝试在实际创建附件前向$ emailMessage对象添加附件。

$emailMessage.Attachments.Add($attachment)  #<---This is causing the error
$emailMessage = New-Object System.Net.Mail.MailMessage

只需重新排列线条,将新对象线放在.Attachments.Add()线之前。

话虽如此,您是否尝试过使用Send-MailMessage cmdlet?它随PowerShell 3.0一起提供,比使用旧的SMTP对象要容易得多。