Repository navigation
Expand file tree
/
Copy pathmail.go
More file actions
executable file
·291 lines (244 loc) · 6.47 KB
/
Copy pathmail.go
File metadata and controls
executable file
·291 lines (244 loc) · 6.47 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package mailer
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"path/filepath"
"time"
apimail "github.com/ainsleyclark/go-mail"
"github.com/vanng822/go-premailer/premailer"
mail "github.com/xhit/go-simple-mail/v2"
)
// Mail holds the information necessary to connect to an SMTP server
type Mail struct {
Domain string
Templates string
Host string
Port int
Username string
Password string
Encryption string
FromAddress string
FromName string
Jobs chan Message
Results chan Result
API string
APIKey string
APIUrl string
}
// Message is the type for an email message
type Message struct {
From string
FromName string
To string
Subject string
Template string
Attachments []string
Data interface{}
}
// Result contains information regarding the status of the sent email message
type Result struct {
Success bool
Error error
}
// ListenForMail listens to the mail channel and sends mail
// when it receives a payload. It runs continually in the background,
// and sends error/success messages back on the Results channel.
// Note that if api and api key are set, it will prefer using
// an api to send mail
func (m *Mail) ListenForMail() {
for {
msg := <-m.Jobs
err := m.Send(msg)
if err != nil {
m.Results <- Result{false, err}
} else {
m.Results <- Result{true, nil}
}
}
}
// Send sends an email message using correct method. If API values are set,
// it will send using the appropriate api; otherwise, it sends via smtp
func (m *Mail) Send(msg Message) error {
if len(m.API) > 0 && len(m.APIKey) > 0 && len(m.APIUrl) > 0 && m.API != "smtp" {
return m.ChooseAPI(msg)
}
return m.SendSMTPMessage(msg)
}
// ChooseAPI chooses api to use (specified in .env)
func (m *Mail) ChooseAPI(msg Message) error {
switch m.API {
case "mailgun", "sparkpost", "sendgrid":
return m.SendUsingAPI(msg, m.API)
default:
return fmt.Errorf("unknown api %s; only mailgun, sparkpost or sendgrid accepted", m.API)
}
}
// SendUsingAPI sends a message using the appropriate API. It can be called directly, if necessary.
// transport can be one of sparkpost, sendgrid, or mailgun
func (m *Mail) SendUsingAPI(msg Message, transport string) error {
if msg.From == "" {
msg.From = m.FromAddress
}
if msg.FromName == "" {
msg.FromName = m.FromName
}
cfg := apimail.Config{
URL: m.APIUrl,
APIKey: m.APIKey,
Domain: m.Domain,
FromAddress: msg.From,
FromName: msg.FromName,
}
driver, err := apimail.NewClient(transport, cfg)
if err != nil {
return err
}
formattedMessage, err := m.buildHTMLMessage(msg)
if err != nil {
return err
}
plainMessage, err := m.buildPlainTextMessage(msg)
if err != nil {
return err
}
tx := &apimail.Transmission{
Recipients: []string{msg.To},
Subject: msg.Subject,
HTML: formattedMessage,
PlainText: plainMessage,
}
// add attachments
err = m.addAPIAttachments(msg, tx)
if err != nil {
return err
}
_, err = driver.Send(tx)
if err != nil {
return err
}
return nil
}
// addAPIAttachments adds attachments, if any, to mail being sent via api
func (m *Mail) addAPIAttachments(msg Message, tx *apimail.Transmission) error {
if len(msg.Attachments) > 0 {
var attachments []apimail.Attachment
for _, x := range msg.Attachments {
var attach apimail.Attachment
content, err := ioutil.ReadFile(x)
if err != nil {
return err
}
fileName := filepath.Base(x)
attach.Bytes = content
attach.Filename = fileName
attachments = append(attachments, attach)
}
tx.Attachments = attachments
}
return nil
}
// SendSMTPMessage builds and sends an email message using SMTP. This is called by ListenForMail,
// and can also be called directly when necessary
func (m *Mail) SendSMTPMessage(msg Message) error {
formattedMessage, err := m.buildHTMLMessage(msg)
if err != nil {
return err
}
plainMessage, err := m.buildPlainTextMessage(msg)
if err != nil {
return err
}
server := mail.NewSMTPClient()
server.Host = m.Host
server.Port = m.Port
server.Username = m.Username
server.Password = m.Password
server.Encryption = m.getEncryption(m.Encryption)
server.KeepAlive = false
server.ConnectTimeout = 10 * time.Second
server.SendTimeout = 10 * time.Second
smtpClient, err := server.Connect()
if err != nil {
return err
}
email := mail.NewMSG()
email.SetFrom(msg.From).
AddTo(msg.To).
SetSubject(msg.Subject)
email.SetBody(mail.TextHTML, formattedMessage)
email.AddAlternative(mail.TextPlain, plainMessage)
if len(msg.Attachments) > 0 {
for _, x := range msg.Attachments {
email.AddAttachment(x)
}
}
err = email.Send(smtpClient)
if err != nil {
return err
}
return nil
}
// getEncryption returns the appropriate encryption type based on a string value
func (m *Mail) getEncryption(e string) mail.Encryption {
switch e {
case "tls":
return mail.EncryptionSTARTTLS
case "ssl":
return mail.EncryptionSSL
case "none":
return mail.EncryptionNone
default:
return mail.EncryptionSTARTTLS
}
}
// buildHTMLMessage creates the html version of the message
func (m *Mail) buildHTMLMessage(msg Message) (string, error) {
templateToRender := fmt.Sprintf("%s/%s.html.tmpl", m.Templates, msg.Template)
t, err := template.New("email-html").ParseFiles(templateToRender)
if err != nil {
return "", err
}
var tpl bytes.Buffer
if err = t.ExecuteTemplate(&tpl, "body", msg.Data); err != nil {
return "", err
}
formattedMessage := tpl.String()
formattedMessage, err = m.inlineCSS(formattedMessage)
if err != nil {
return "", err
}
return formattedMessage, nil
}
// buildPlainTextMessage creates the plaintext version of the message
func (m *Mail) buildPlainTextMessage(msg Message) (string, error) {
templateToRender := fmt.Sprintf("%s/%s.plain.tmpl", m.Templates, msg.Template)
t, err := template.New("email-html").ParseFiles(templateToRender)
if err != nil {
return "", err
}
var tpl bytes.Buffer
if err = t.ExecuteTemplate(&tpl, "body
4865
", msg.Data); err != nil {
return "", err
}
plainMessage := tpl.String()
return plainMessage, nil
}
// inlineCSS takes html input as a string, and inlines css where possible
func (m *Mail) inlineCSS(s string) (string, error) {
options := premailer.Options{
RemoveClasses: false,
CssToAttributes: false,
KeepBangImportant: true,
}
prem, err := premailer.NewPremailerFromString(s, &options)
if err != nil {
return "", err
}
html, err := prem.Transform()
if err != nil {
return "", err
}
return html, nil
}