'Why do I get a 'cannot call a method on a null-valued expression' error?

I want to send an email using powershell and it's working perfectly but when I try adding attachment its giving me an error. This is the code

$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("[email protected]", "$$$$$$");
$SMTPClient.EnableSsl = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$attachment = "$env:appdata\Microsoft\dump\dump.zip"
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$SMTPServer = "smtp.gmail.com"
$Body = "Tricknology Test"
$Subject = "Test" 

and this is the error

At line:4 char:1
+ $message.Attachments.Add($attach)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull```


Solution 1:[1]

As commented, you need to get the order of things right. PowerShell reads and executes code from top to bottom and in your case, you are trying to perform the .Send() method on a variable that hasn't been defined yet..

You are also using a $message variable that has not been defined anywhere in the code.

Try

# step 1: create the object
$SMTPServer = 'smtp.gmail.com'
$SMTPClient = New-Object System.Net.Mail.SmtpClient($SMTPServer, 587)

# step 2: set the object's properties
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential('[email protected]', '$$$$$$')
$SMTPClient.EnableSsl = $true

# step 3: create an attachment object and set it to your file
$attachment = Join-Path -Path $env:APPDATA -ChildPath 'Microsoft\dump\dump.zip'
$attach     = New-Object System.Net.Mail.Attachment($attachment)

# step 4: create a Message object and add the attachment to it
$EmailFrom = '[email protected]'
$EmailTo   = '[email protected]'
$Body      = 'Tricknology Test'
$Subject   = 'Test'
$message   = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)
$message.Attachments.Add($attach)

# step finally: send the email and clean up
$SMTPClient.Send($message)
$attach.Dispose()
$message.Dispose()
$SMTPClient.Dispose()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Theo