summaryrefslogtreecommitdiff
path: root/internal/quorum/notify.go
blob: 7761b4dff9b992bcfb66d0fe217d9738eefd24a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package quorum

import (
	"fmt"
	"log"
	"net/smtp"

	"codeberg.org/snonux/gorum/internal/config"
)

func notifyEnabled(conf config.Config) bool {
	return conf.EmailFrom != "" && conf.EmailTo != "" && conf.SMTPServer != ""
}

func notify(conf config.Config, subject, body string) error {
	if !notifyEnabled(conf) {
		return nil
	}

	log.Println("notify:", subject, body)

	headers := map[string]string{
		"From":         conf.EmailFrom,
		"To":           conf.EmailTo,
		"Subject":      subject,
		"MIME-Version": "1.0",
		"Content-Type": "text/plain; charset=\"utf-8\"",
	}

	header := ""
	for k, v := range headers {
		header += fmt.Sprintf("%s: %s\r\n", k, v)
	}

	message := header + "\r\n" + body
	log.Println("Using SMTP server", conf.SMTPServer)

	return smtp.SendMail(conf.SMTPServer, nil, conf.EmailFrom,
		[]string{conf.EmailTo}, []byte(message))
}

func notifyError(conf config.Config, err error) {
	if notifyEnabled(conf) {
		if err := notify(conf, fmt.Sprintf("GORUM: An error occured: %v", err), err.Error()); err != nil {
			log.Println("error:", err)
		}
	}
}