This repository has been archived by the owner on Nov 18, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
mailme.go
193 lines (169 loc) · 4.23 KB
/
mailme.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package mailme
import (
"bytes"
"errors"
"html/template"
"io"
"log"
"net/http"
"strings"
"sync"
"time"
"gopkg.in/gomail.v2"
"github.com/sirupsen/logrus"
)
// TemplateRetries is the amount of time MailMe will try to fetch a URL before giving up
const TemplateRetries = 3
// TemplateExpiration is the time period that the template will be cached for
const TemplateExpiration = 10 * time.Second
// Mailer lets MailMe send templated mails
type Mailer struct {
From string
Host string
Port int
User string
Pass string
BaseURL string
LocalName string
FuncMap template.FuncMap
cache *TemplateCache
Logger logrus.FieldLogger
}
// Mail sends a templated mail. It will try to load the template from a URL, and
// otherwise fall back to the default
func (m *Mailer) Mail(to, subjectTemplate, templateURL, defaultTemplate string, templateData map[string]interface{}) error {
if m.FuncMap == nil {
m.FuncMap = map[string]interface{}{}
}
if m.cache == nil {
m.cache = &TemplateCache{
templates: map[string]*MailTemplate{},
funcMap: m.FuncMap,
logger: m.Logger,
}
}
tmp, err := template.New("Subject").Funcs(template.FuncMap(m.FuncMap)).Parse(subjectTemplate)
if err != nil {
return err
}
subject := &bytes.Buffer{}
err = tmp.Execute(subject, templateData)
if err != nil {
return err
}
body, err := m.MailBody(templateURL, defaultTemplate, templateData)
if err != nil {
return err
}
mail := gomail.NewMessage()
mail.SetHeader("From", m.From)
mail.SetHeader("To", to)
mail.SetHeader("Subject", subject.String())
mail.SetBody("text/html", body)
dial := gomail.NewDialer(m.Host, m.Port, m.User, m.Pass)
if m.LocalName != "" {
dial.LocalName = m.LocalName
}
return dial.DialAndSend(mail)
}
type MailTemplate struct {
tmp *template.Template
expiresAt time.Time
}
type TemplateCache struct {
templates map[string]*MailTemplate
mutex sync.Mutex
funcMap template.FuncMap
logger logrus.FieldLogger
}
func (t *TemplateCache) Get(url string) (*template.Template, error) {
cached, ok := t.templates[url]
if ok && (cached.expiresAt.Before(time.Now())) {
return cached.tmp, nil
}
data, err := t.fetchTemplate(url, TemplateRetries)
if err != nil {
return nil, err
}
return t.Set(url, data, TemplateExpiration)
}
func (t *TemplateCache) Set(key, value string, expirationTime time.Duration) (*template.Template, error) {
parsed, err := template.New(key).Funcs(t.funcMap).Parse(value)
if err != nil {
return nil, err
}
cached := &MailTemplate{
tmp: parsed,
expiresAt: time.Now().Add(expirationTime),
}
t.mutex.Lock()
t.templates[key] = cached
t.mutex.Unlock()
return parsed, nil
}
func (t *TemplateCache) fetchTemplate(url string, triesLeft int) (string, error) {
client := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Get(url)
if err != nil && triesLeft > 0 {
return t.fetchTemplate(url, triesLeft-1)
}
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == 200 { // OK
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil && triesLeft > 0 {
return t.fetchTemplate(url, triesLeft-1)
}
if err != nil {
return "", err
}
return string(bodyBytes), err
}
if triesLeft > 0 {
return t.fetchTemplate(url, triesLeft-1)
}
return "", errors.New("Unable to fetch mail template")
}
func (m *Mailer) MailBody(url string, defaultTemplate string, data map[string]interface{}) (string, error) {
if m.FuncMap == nil {
m.FuncMap = map[string]interface{}{}
}
if m.cache == nil {
m.cache = &TemplateCache{templates: map[string]*MailTemplate{}, funcMap: m.FuncMap}
}
var temp *template.Template
var err error
if url != "" {
var absoluteURL string
if strings.HasPrefix(url, "http") {
absoluteURL = url
} else {
absoluteURL = m.BaseURL + url
}
temp, err = m.cache.Get(absoluteURL)
if err != nil {
log.Printf("Error loading template from %v: %v\n", url, err)
}
}
if temp == nil {
cached, ok := m.cache.templates[url]
if ok {
temp = cached.tmp
} else {
temp, err = m.cache.Set(url, defaultTemplate, 0)
if err != nil {
return "", err
}
}
}
buf := &bytes.Buffer{}
err = temp.Execute(buf, data)
if err != nil {
return "", err
}
return buf.String(), nil
}