Error using Send-MailMessage as NT Authority\System

Encountered this issue while writing a scheduled script that the customer wanted e-mail notifications for. Due to previous dependencies this script was running as the system (NT Authority\System).

I created the code I wanted to use and tested it with my account. Everything worked as expected however when running the scheduled task no message was sent.

To troubleshoot the issue I launched PowerShell from PSExec to test the code using the system account and I received the following error:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Despite the SMTP-server being configured to allow anonymous connections from the host the connections were refused. The cause is that PowerShell will send the credentials for the user running the script automatically. My user was allowed to send messages through the relay however the system account was not. So how do we send the message anonymously?

By creating the following credential object I was able to solve the issue:

$User = "anonymous"
$Password = ConvertTo-SecureString "anonymous" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($User, $Password)

Add the credential parameter to “Send-MailMessage” and things should be just fine.

Send-MailMessage -From -To -Subject "This is a test!" -SmtpServer -Credential $Cred

Leave a Reply

Your email address will not be published. Required fields are marked *