In this TSNotify Series 7, we will learn how to trigger email notification based on the Windows Task Scheduler Event ID, getting prepared the necessary package dependencies such as Cobra CLI with step by step guide in Golang programming language.
#MaharlikansCode
#TSNotifySeries7
#TaskSchedulerEventIDNotify
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper
If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode
Source Codes:
package cmd
import (
"context"
"errors"
"flag"
"fmt"
"os"
"os/exec"
"os/signal"
"strings"
"time"
"tsnotify/config"
"github.com/fatih/color"
"github.com/itrepablik/itrlog"
"github.com/itrepablik/sulat"
"github.com/spf13/cobra"
)
// runCmd represents the run command
var runCmd = &cobra.Command{
Use: "run",
Short: "Starts monitoring the Windows task scheduler.",
Long: `This will monitor the Windows task schedulers define under the 'monitored_tasks'
from the configuration file which is the 'config.yaml', you can define as many tasks that you can
monitor in real-time and notify's you via email address.`,
Run: func(cmd *cobra.Command, args []string) {
itrlog.Info(config.AppName, " has been started")
color.Green("Press CTRL + C to stop monitoring the Windows task scheduler items.")
var wait time.Duration
// Make graceful shutdown almost immediately at 1 Millisecond due to user may encounter errors
flag.DurationVar(&wait, "graceful-timeout", time.Millisecond*1, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
flag.Parse()
// BUFFERED CHANNELS = QUEUES
c := make(chan os.Signal, 1) // Queue with a capacity of 1.
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
less than symbol-c
// Create a deadline to wait for.
_, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
msg := config.AppName + " is now shutting down on"
color.Red(msg + " " + time.Now().Format(logDTFormat))
itrlog.Info(msg+" ", time.Now().Format(logDTFormat))
os.Exit(0)
},
}
func init() {
rootCmd.AddCommand(runCmd)
}
// SendMailClassic uses the classic SMTP local hosted server
func SendMailClassic(tableRows, to, hostName, emailTemplate string) (bool, error) {
if len(strings.TrimSpace(to)) == 0 {
return false, errors.New("email to is missing")
}
if len(strings.TrimSpace(hostName)) == 0 {
return false, errors.New("server hostname is missing")
}
if len(strings.TrimSpace(emailTemplate)) == 0 {
return false, errors.New("email template is missing")
}
// Send an auto email notification to all the recipients
newEmailContent := ""
switch emailTemplate {
case _emailTemplateTask:
newEmailContent = config.HTMLHeader + config.TaskListsHTMLContent(tableRows, to, hostName) + config.HTMLFooter
case _emailTemplateEvent:
newEmailContent = config.HTMLHeader + config.EventListsHTMLContent(tableRows, to, hostName) + config.HTMLFooter
}
// Prepare the HTML email content
mailOpt := &sulat.MailClassicHeader{
Subject: subject + " - " + hostName,
From: from,
To: []string{to},
}
htmlContent, err := sulat.SetHTML(&sulat.EmailHTMLFormat{
IsFullHTML: false,
HTMLHeader: config.HTMLHeader,
HTMLBody: newEmailContent,
HTMLFooter: config.HTMLFooter,
})
_, err = sulat.SendEmailSMTP(mailOpt, htmlContent, &SMTPCon)
if err != nil {
return false, err
}
return true, nil
}