email alarm now sends emails

This commit is contained in:
Christopher Ramey 2021-01-20 07:31:22 -09:00
parent bcf0e91d0b
commit afcdef029e
2 changed files with 61 additions and 2 deletions

View File

@ -2,6 +2,8 @@ package alarm
import (
"fmt"
"net/smtp"
"os"
"strings"
)
@ -22,13 +24,64 @@ type AlarmEmail struct {
}
func NewAlarmEmail(name string) *AlarmEmail {
host, _ := os.Hostname()
if host == "" {
host = "localhost"
}
return &AlarmEmail{
Type: "email", Name: name,
From: "alrm@" + host, SMTP: "localhost:25",
}
}
func (a *AlarmEmail) Alarm() error {
fmt.Printf("email alarm\n")
c, err := smtp.Dial(a.SMTP)
if err != nil {
return err
}
helo := "localhost"
tspl := strings.Split(a.From, "@")
if len(tspl) > 1 {
helo = tspl[1]
}
err = c.Hello(helo)
if err != nil {
return err
}
err = c.Mail(a.From)
if err != nil {
return err
}
for _, to := range a.To {
err = c.Rcpt(to)
if err != nil {
return err
}
}
m, err := c.Data()
if err != nil {
return err
}
msg := fmt.Sprintf("From: %s\r\n", a.From)
msg += fmt.Sprintf("To: %s\r\n", strings.Join(a.To, ";"))
msg += fmt.Sprintf("Subject: %s\r\n", "test subject")
_, err = fmt.Fprintf(m, "%s", msg)
if err != nil {
return err
}
err = m.Close()
if err != nil {
return err
}
err = c.Quit()
if err != nil {
return err
}
return nil
}
@ -50,10 +103,16 @@ func (a *AlarmEmail) Parse(tk string) (bool, error) {
}
case TK_FROM:
if strings.TrimSpace(tk) == "" {
return false, fmt.Errorf("from address cannot be empty")
}
a.From = tk
a.state = TK_NONE
case TK_SMTP:
if strings.TrimSpace(tk) == "" {
return false, fmt.Errorf("smtp server cannot be empty")
}
a.SMTP = tk
a.state = TK_NONE

2
alrmrc
View File

@ -3,7 +3,7 @@ set interval 30s
alarm people email
to test1@localhost
to test2@localhost
smtp localhost
smtp localhost:25
from alrm@localhost
monitor group webservers