-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
100 lines (86 loc) · 2.29 KB
/
server.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
package main
import (
"bytes"
"encoding/json"
"fmt"
html "html/template"
text "text/template"
log "github.com/Sirupsen/logrus"
"github.com/go-gomail/gomail"
"github.com/hyperboloide/dispatch"
"github.com/hyperboloide/qmail/client"
"github.com/russross/blackfriday"
)
// SMTPConf contains connection informations
type SMTPConf struct {
Host string
Port int
User string
Password string
}
// Mailer reads mails from the queue and send message to smtp
type Mailer struct {
SMTP SMTPConf
Queue dispatch.PersistantQueue
Sender string
Templates *text.Template
Body *html.Template
}
func doError(err error, email *client.Mail) error {
if email != nil {
log.WithFields(map[string]interface{}{
"template": email.Template,
"dests": email.Dests,
"files": email.Files,
}).Error(err)
}
return err
}
// Listenner is called by the Listen polling function of the queue when a
// message is available
func (m Mailer) Listenner(buff []byte) error {
email := &client.Mail{}
if err := json.Unmarshal(buff, email); err != nil {
return doError(err, nil)
}
textBuff := &bytes.Buffer{}
tmplName := fmt.Sprintf("%s.md", email.Template)
if t := m.Templates.Lookup(tmplName); t == nil {
return doError(fmt.Errorf("template '%s' not found", tmplName), email)
} else if err := t.Execute(textBuff, email.Data); err != nil {
return doError(err, email)
}
md := blackfriday.MarkdownCommon(textBuff.Bytes())
htmlBuff := &bytes.Buffer{}
err := m.Body.Execute(
htmlBuff,
html.HTML(string(md[:])))
if err != nil {
return doError(err, email)
}
messages := []*gomail.Message{}
for _, dest := range email.Dests {
gm := gomail.NewMessage()
gm.SetHeader("From", m.Sender)
gm.SetHeader("To", dest)
gm.SetHeader("Subject", email.Subject)
gm.SetBody("text/plain", string(textBuff.Bytes()[:]))
gm.AddAlternative("text/html", string(htmlBuff.Bytes()[:]))
for _, f := range email.Files {
gm.Attach(f)
}
messages = append(messages, gm)
}
d := gomail.NewDialer(
m.SMTP.Host,
m.SMTP.Port,
m.SMTP.User,
m.SMTP.Password)
if err := d.DialAndSend(messages...); err != nil {
return doError(err, email)
}
log.WithFields(map[string]interface{}{
"template": email.Template,
}).Infof("Message sent to '%d' recipients", len(email.Dests))
return nil
}