-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailer.go
105 lines (98 loc) · 2.24 KB
/
mailer.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"fmt"
"log"
"net/smtp"
"net/url"
"os/exec"
)
// Mailer struct
type Mailer struct {
gmail, pass, to string
}
// BuildAndSendEmail send alert email
func (m *Mailer) BuildAndSendEmail(errors []error) {
if m.to != "" {
var (
count = len(errors)
subject string
body string
)
if count == 1 {
urlErr, ok := errors[0].(*url.Error)
if ok {
subject = fmt.Sprintf("'%s' is unreachable", urlErr.URL)
} else {
subject = "A site is unreachable"
}
} else {
subject = fmt.Sprintf("%d sites are unreachable", count)
}
for _, error := range errors {
body += fmt.Sprintf("* %s\n\n", error.Error())
}
err := m.SendMail(subject, body)
if err != nil {
log.Println(err)
}
}
}
// SendMail send a email
func (m *Mailer) SendMail(subject, body string) error {
if m.gmail == "" {
return m.sendEmailWithMail(subject, body)
}
return m.sendEmailWithGmail(subject, body)
}
func (m *Mailer) sendEmailWithGmail(subject, body string) error {
msg := "From: Bulldog <bulldog>\n" +
"To: " + m.to + "\n" +
"Subject: [Bulldog] " + subject + "\n\n" +
body
err := smtp.SendMail("smtp.gmail.com:587",
smtp.PlainAuth("", m.gmail, m.pass, "smtp.gmail.com"),
m.gmail, []string{m.to}, []byte(msg))
if err != nil {
return err
}
return nil
}
func (m *Mailer) sendEmailWithMail(subject, body string) error {
c1 := exec.Command("echo", body)
c2 := exec.Command("mail", "-s [Bulldog] "+subject, "-r Bulldog <bulldog>", m.to)
c2.Stdin, _ = c1.StdoutPipe()
err1 := c1.Start()
err2 := c2.Run()
err3 := c1.Wait()
if err1 != nil {
return err1
}
if err2 != nil {
return err2
}
if err3 != nil {
return err3
}
return nil
}
// func errorToEmoji(err error) string {
// if strings.Contains(err.Error(), "Client.Timeout exceeded") {
// return "⌛️"
// }
// if strings.Contains(err.Error(), "unsupported protocol scheme") {
// return "😓"
// }
// if strings.Contains(err.Error(), "no such host") {
// return "🛑"
// }
// if strings.Contains(err.Error(), "status code is 403") {
// return "🔒"
// }
// if strings.Contains(err.Error(), "status code is 404") {
// return "🔎"
// }
// if strings.Contains(err.Error(), "status code is 500") {
// return "🆘"
// }
// return "⚠️"
// }