Powershell – Sending unauthenticated mail through MS Exchange with powershell (Windows Server 2008 R2)

exchange-2010powershellwindows-server-2008-r2

I'm trying use Task Scheduler to run a powershell script and emails the output of a few commands. I'm using "Send-MailMessage" to do this. When I run the scheduled task with a domain admin account, I receive the emails just fine, but when I use a service account, the emails do not come through.

The service account I am using has both "Logon as a Service" and "Log on as Batch Job". It also has local admin rights on the server I am running this from.

Something to note: I have used telnet to send email through the SMTP server I am using and was able to send an unauthenticated email, so the problem is not an authentication problem with the SMTP server.

What credentials am I missing on this service account? Is there anything else I could be missing?

Thanks for the help!

Best Answer

When you submit an email through telnet and choose not to authenticate, the server assumes that you are anonymous (aka the well-known NT AUTHORITY\Anonymous logon or S-1-5-7).

When Send-MailMessage submits an email, it will ALWAYS try to authenticate the session. If a set of credentials is not specified, it will assume that the current users network credentials is to be used, and authenticates as the service account running the PowerShell script.

The service account is neither anonymous, an Exchange User nor an Exchange Organization Administrator and will not be permitted to submit the email.

The work around this, you'll need a PSCredential object:

$anonUsername = "anonymous"
$anonPassword = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
$anonCredentials = New-Object System.Management.Automation.PSCredential($anonUsername,$anonPassword)

Send-MailMessage -to "Big Boss <ceo@example.com>" -from "Me <advis12@example.com>" -subject "It's working! EOM" -credential $anonCredentials

Now your script is sending mails anonymously as well :-)


Another (and more secure) option is to give the service account in question the required permissions on a receive connector:

$RC = Get-ReceiveConnector "ConnectorNameGoesHere" 
$RC | Add-ADPermission -User "DOMAIN\ServiceAcc01" -ExtendedRights ms-Exch-SMTP-Submit,ms-Exch-SMTP-Accept-Authoritative-Domain-Sender

If you need to transfer files that will potentially be removed by content filtering or the likes you can also allow it to bypass anti-spam mechanisms:

$RC | Add-ADPermission -User "DOMAIN\ServiceAcc01" -ExtendedRights ms-Exch-Bypass-Anti-Spam

If you want it to send emails to recipients outside your own Exchange Organization you'll need to allow that as well:

$RC | Add-ADPermission -User "DOMAIN\ServiceAcc01" -ExtendedRights ms-Exch-SMTP-Accept-Any-Recipient
Related Topic