简体   繁体   中英

Cannot send powershell email - You cannot call a method on a null-valued expression

I have this working on my local machine, but when I try it on another machine, that has the same files in the same place etc, it fails with this error.

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 )
}

This is the output

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

You have two lines of code in the wrong order:

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

Should be:

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

You need to instantiate your object before you can reference its members.

You're trying to add an attachment to the $emailMessage object before you actually create it.

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

Just rearrange the lines, put the New-Object line before the .Attachments.Add() line.

With that being said, have you tried using the Send-MailMessage cmdlet? It shipped with PowerShell 3.0 and is much, much much easier than using the old SMTP object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM