-
Notifications
You must be signed in to change notification settings - Fork 1
/
email.go
70 lines (63 loc) · 1.34 KB
/
email.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
package main
import (
"gopkg.in/mail.v2"
"log"
"os"
"time"
)
var emailChan chan *mail.Message
func init() {
emailChan = make(chan *mail.Message)
go func() {
d := mail.NewDialer(
os.Getenv("SMARTALARM_EMAILHOST"),
587,
os.Getenv("SMARTALARM_EMAILADDR"),
os.Getenv("SMARTALARM_EMAILPASS"),
)
d.StartTLSPolicy = mail.MandatoryStartTLS
var s mail.SendCloser
var err error
open := false
for {
select {
case m, ok := <-emailChan:
log.Println("Sending email", m)
if !ok {
return
}
if !open {
if s, err = d.Dial(); err != nil {
panic(err)
}
open = true
}
if err := mail.Send(s, m); err != nil {
log.Println(err)
return
}
// Increment "use" counter in DB
go func(emails []string) {
if len(emails) != 1 {
log.Println("Wrong number of emails, not updating DB")
return
}
_, err := db.Exec("UPDATE smartalarm_emails SET uses=uses+1 WHERE email=?", emails[0])
if err != nil {
log.Println(err)
}
}(m.GetHeader("To"))
// Close the connection to the SMTP server if no email was sent in
// the last 5 seconds.
case <-time.After(5 * time.Second):
if open {
log.Println("Closing SMTP connection")
if err := s.Close(); err != nil {
log.Println(err)
}
open = false
}
}
}
}()
}