Vishal
Vishal

Reputation: 178

Powershell Script not able to send email via Outlook using Task Scheduler

I have a script which is fetching the latest event log from the remote machine. Send an event log details via outlook to specific group of people. The script is working fine on running through Powershell ISE but not sending email using task scheduler. Any help would be appreciated. Thanks

Script As below:

$Recipients="[email protected]","[email protected]"

Foreach ($name in $Recipients) {
    $Outlook = New-Object -ComObject Outlook.Application

    $Mail = $Outlook.CreateItem(0)
    $Mail.Recipients.Add($name)
    $Mail.Subject ="Testing"
    $Mail.Body ="Demo"
    Write-Host "Sending Email"
    $Mail.Send()
}

Upvotes: 3

Views: 2989

Answers (3)

Eugene Astafiev
Eugene Astafiev

Reputation: 49395

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.

 $From = "[email protected]"
 $To = "[email protected]"
 $Cc = "[email protected]"
 $Attachment = "C:\temp\Some random file.txt"
 $Subject = "Email Subject"
 $Body = "Insert body text here"
 $SMTPServer = "smtp.gmail.com"
 $SMTPPort = "587"
 Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
 -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
 -Credential (Get-Credential) -Attachments $Attachment

Also you may consider using EWS, see EWS Managed API, EWS, and web services in Exchange for more information.

Upvotes: 3

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66215

Task Scheduler runs as a service - and no Office app (Outlook included) can be used in a service.

Upvotes: 2

bluuf
bluuf

Reputation: 1001

You should just use Send-MailMessage instead of trying to use the Outlook COM object for this. This way you don't rely on a mail profile and other settings (which need to be set in Outlook under the user which you use to run the task). I also see some weird things in your code : for each recipient you create a new COM Outlook COM object, and then you try to send a mail : moving the For Loop to trigger After the creation of the Outlook COM object seems more logical.

Upvotes: 0

Related Questions