0
votes

have searched around but cant get this to work. I have as PS script that sends email on server boot. It works when I run it through a cmd file. I have setup a Task under Task Scheduler to run that cmd file and selected 'Run whether user is logged in or not' and also 'Run wit highest privileges'

When I restart the PC it doesnt run the script.

The script only gets run when I log in.

Any ideas please?


When computer starts. Sent output to log as suggested get this:


Exception calling "Send" with "4" argument(s): "Failure sending mail." At C:\Users\ravlo\sendEmail.ps1:9 char:1 + $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SmtpException


Full Script is this:


$EmailFrom = "x"
$EmailTo = "y"
$Subject = "SERVER JUST REBOOTED"
$Body = "z"
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("emaillogin", "emailpwd");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

Runs OK when I actually log in.

1
What Trigger did you select for the task? When the computer starts or When I log on? What Actions did you configure for the task? What does the History/Last Run Result show for that task? Are you sure the script isn't running at all vs. only the email part of it is failing? Can you write to a log within the script to see what it's doing and when? I don't think Run with highest privileges is necessary, and, depending on your email system, the user as which the script is run might not be significant. - Lance U. Matthews
hi edited original post with details. - JKL
Does this answer your question? Sending mail using SmtpClient in .net - iRon

1 Answers

0
votes

Can you test your mail server accessibility before you execute Send() ? You can add

if ((Test-NetConnection -ComputerName $SMTPServer -Port 25).TcpTestSucceeded) {
    $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
} else {
    Write-Output "SMTP Server not accessible"
}

If you have Windows Pro and higher, you can use Group Policy startup scripts in Computer configuration scope.