Task scheduler powershell code not sending email.

Welcome Forums Pester Task scheduler powershell code not sending email.

This topic contains 1 reply, has 2 voices, and was last updated by

 
Keymaster
6 months, 1 week ago.

  • Author
    Posts
  • #101896
    SK

    Participant
    Points: 0
    Rank: Member

    Param (
    [string]$Path = "\\abcd\efgh\ijkl\mnop",
    [string]$SMTPServer = "abcd.efgh.org",
    [string]$From = "gkvdv@erb.org",
    [string]$To = "bwerbp@erb.org",
    [string]$Subject = "XXXXXX"
    )
    $file_attachments = @()

    $SMTPMessage = @{
    To = $To
    From = $From
    Subject = "$Subject at $Path"
    Smtpserver = $SMTPServer
    }

    $File = Get-ChildItem $Path | Where { ($_.LastWriteTime -ge [datetime]::Now.Addminutes(-1440) ) -and ( $_.BaseName -like 'yyyy*') }
    If ($File)
    { $SMTPBody = "`nThe following files have recently been added/changed:`n`n"
    $File | ForEach { $SMTPBody += "$($_.FullName)`n" }
    $File | ForEach {$file_attachments += $_.FullName}

    Send-MailMessage @SMTPMessage -Body $SMTPBody -Attachments $file_attachments

    }

    The above code sends out an email when I run it in the powershell window.
    But I schedule it in a task scheduler it runs successfully but not send out an email.

    Under task scheduler tabs
    Action:
    Program/script : powershell
    Add arguments ()optional‌:-ExecutionPolicy Bypass -file "\\abcd\efgh\ijkl\mnop\wgsgd.ps1"‌‌‌‌‌‌‌‌‌

    Help is appreciated.
    Thanks
    ‌‌‌‌

  • #102176

    Keymaster
    Points: 1,704
    Helping HandTeam Member
    Rank: Community Hero

    Task Scheduler tends to run under LocalSystem. It's likely your mail server is rejecting the connection from the unauthenticated user.

The topic ‘Task scheduler powershell code not sending email.’ is closed to new replies.