Thursday, January 12, 2017

Sending Messages as Scheduled Task

Hi folks,

I would love to share with you about my recent adventure on configuring scheduled task for running some Exchange-related scheduled tasks using PowerShell. To avoid using excessive permissions for an account that will run the scheduled task I created user account in AD with the default group membership (Domain Users). This account has been granted "Logon as batch job" rights on a server where the scheduled task will run. The script included a line to send results of the script execution to an admin's email address, something like below:

Send-MailMessage -from sender@contoso.com -to recipient@contoso.com -subject "Scheduled Task Report" -body ($bb | out-string) -smtpServer 'server01.contoso.com' -bodyashtml

However, emails wouldn't arrive. There was nothing in the task to indicate failure of it as it ran smootly. So the following line was added to the beginning of the script:

Start-Transcript -Path C:\Scripts\executionTranscript.txt

And at the end of the script I appended:

Stop-Transcript

When checking execution transcript I would see the error as below:

Send-MailMessage : Mailbox unavailable. The server response was: 5.7.1 Client does not have permissions to send as
this sender
At D:\ML\Scripts\QueueStatus.ps1:16 char:1
+ Send-MailMessage -from sender@contoso.com -to recipient@contoso.com ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcept
   ion
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

What it says that service account can send as sender@contoso.com (of course there should be your sender address here). To resolve this issue scheduled task will need to be reconfigured to run as sender@contoso.com with granting rights as mentioned above. Alternatively, service account can be mail or mailbox enabled (I would recommend the former) and script updated to send email as service account.

You will need to run the below code to mail-enable the service account:

Enable-MailUser -Identity "CONTOSO\serviceaccount" -PrimarySMTPAddress "serviceaccount@contoso.com" -ExternalEmailAddress "serviceaccount@contoso.com"

Then you will need to reconfigure your code to something as below:

Send-MailMessage -from serviceaccount@contoso.com -to recipient@contoso.com -subject "Scheduled Task Report" -body ($bb | out-string) -smtpServer 'server01.contoso.com' -bodyashtml


I hope you will find this useful when troubleshooting issue as this one.

Enjoy!

No comments:

Post a Comment