4

I'm trying to invoke an inline powershell script from Task Scheduler to send an email when a particular event is triggered. I can't use the native 'Send an e-mail' action in the Task Scheduler action window because the SMTP server requires SSL and there's no way to specify this in the action window. So I'm looking to 'Start a program' and invoke something to send email but I want to avoid using 3rd party applications such as sendEmail if possible so was hoping to be able to invoke an inline powershell script similar to the following.

Setting the 'Program/script' field to powershell and the arguments field to:

-Command "{Send-MailMessage -From "Name <[email protected]>" -To "[email protected]" -Subject "Test Subject" -Body "Test body at $(Get-Date -Format "dd/MM/yyyy")." -SmtpServer "smtp.domain.com" -UseSSL}"

This obviously doesn't work due to the nested quotes etc, so I've been trying different variations in command prompt, but I can't for the life of me figure out which characters I need to escape and how to escape them.

Any help would be much appreciated.

1

2 Answers 2

10
  1. Just take a look to the example section of "powershell /?" ...

PowerShell -Command "& {Get-EventLog -LogName Application}"


  1. Take a look how to use quotes.

PowerShell -Command "& {Send-MailMessage -From 'Name ' -To '[email protected]' -Subject 'Test Subject' -Body ('Test body at {0}.' -f (Get-Date -Format 'dd/MM/yyyy')) -SmtpServer 'smtp.domain.com' -UseSSL}"

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's great. One thing I forgot to say is that I'm trying to put newline characters in the body of the email too - I would normally use 'r'n (had to use single quotes here instead of actual backtick characters due to SO's syntax highlighting) but the backtick characters are being treated as literals as they're inside a single quoted string. Any ideas how I would do that?
5

This should work:

powershell -Command 'Send-MailMessage -From "Name <[email protected]>" -To "[email protected]" -Subject "Test Subject" -Body "Test body at $(Get-Date -Format "dd/MM/yyyy")." -SmtpServer "smtp.domain.com" -UseSSL'

You can use single quotes around double quotes, and you don't need the curly brackets around the command.

3 Comments

it wasn't mentioned, but there may also be a need to pass credentials. it's rare to be able to send to an smtp server without authentication.
This command just print string on console instead of executing it.
The command should be wrapped in double quotes. That means that inner double quotes need to be either escaped or replaced with single quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.