-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.go
778 lines (720 loc) · 18.7 KB
/
message.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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
package email
import (
"bytes"
"errors"
"fmt"
htpl "html/template"
"io/ioutil"
"mime"
"path/filepath"
"strconv"
"sync"
ttpl "text/template"
"time"
"github.com/agext/uuid"
)
// CTE represents a "Content-Transfer-Encoding" method identifier.
type CTE byte
const (
// AutoCTE leaves it up to the package to determine CTE
AutoCTE CTE = iota
// QuotedPrintable indicates "quoted-printable" CTE
QuotedPrintable
// Base64 indicates "base64" CTE
Base64
)
var (
now = time.Now
newUUID = func() []byte {
return []byte(uuid.New().Hex())
}
)
// Message represents all the information necessary for composing an email message with optional
// external data, and sending it via a Sender.
type Message struct {
sync.RWMutex
domain []byte
subject []byte
subjectTpl *ttpl.Template
sender *Sender
from, replyTo *Address
to, cc, bcc addrList
parts []*part
text, html *part
attachments []*attachment
errors []error
prepared bool
}
// Domain sets the domain portion of the generated message Id.
//
// If not specified, the domain is extracted from the sender email address - which is
// the right choice for most applications.
func (m *Message) Domain(domain string) *Message {
m.Lock()
defer m.Unlock()
m.domain = []byte(domain)
return m
}
func (m *Message) setSender(s *Sender) *Message {
m.Lock()
defer m.Unlock()
m.sender = s
return m
}
func (m *Message) Sender(s *Sender) *Message {
m.setSender(s)
return m
}
// Subject sets the text for the subject of the message.
func (m *Message) Subject(subject interface{}) *Message {
m.Lock()
defer m.Unlock()
switch subject := subject.(type) {
case string:
m.subject = []byte(subject)
m.subjectTpl = nil
case []byte:
m.subject = subject
m.subjectTpl = nil
case *ttpl.Template:
m.subject = nil
m.subjectTpl = subject
default:
m.errors = append(m.errors, errors.New("invalid argument type"))
}
return m
}
// SubjectTemplate sets a template for the subject of the message.
func (m *Message) SubjectTemplate(tpl string) *Message {
var (
t *ttpl.Template
err error
)
if tpl != "" {
t, err = ttpl.New("").Parse(tpl)
if err != nil {
m.errors = append(m.errors, errors.New("invalid subject template:\n"+tpl+"\nerror: "+err.Error()))
return m
}
}
m.Lock()
defer m.Unlock()
m.subjectTpl = t
return m
}
// From sets the From: email address.
func (m *Message) From(addr *Address) *Message {
if addr != nil && !SeemsValidAddr(addr.Addr) {
addr = nil
}
m.Lock()
defer m.Unlock()
m.from = addr
return m
}
// To sets the To: email address(es). Last call overrides any previous calls, replacing rather than
// adding to the list.
func (m *Message) To(addr ...*Address) *Message {
lst := make(addrList, 0, len(addr))
for _, a := range addr {
if a != nil && SeemsValidAddr(a.Addr) {
lst = append(lst, a)
}
}
m.Lock()
defer m.Unlock()
m.to = lst
return m
}
// Cc sets the (optional) Cc: email addresses. Last call overrides any previous calls, replacing rather than
// adding to the list.
func (m *Message) Cc(addr ...*Address) *Message {
lst := make(addrList, 0, len(addr))
for _, a := range addr {
if a != nil && SeemsValidAddr(a.Addr) {
lst = append(lst, a)
}
}
m.Lock()
defer m.Unlock()
m.cc = lst
return m
}
// Bcc sets the (optional) Bcc: email addresses. Last call overrides any previous calls, replacing rather than
// adding to the list.
func (m *Message) Bcc(addr ...*Address) *Message {
lst := make(addrList, 0, len(addr))
for _, a := range addr {
if a != nil && SeemsValidAddr(a.Addr) {
lst = append(lst, a)
}
}
m.Lock()
defer m.Unlock()
m.bcc = lst
return m
}
// ReplyTo sets the (optional) Reply-To: email address. A `*Address` argument is expected for
// consistency, although only the email address part is used.
func (m *Message) ReplyTo(addr *Address) *Message {
if addr != nil && !SeemsValidAddr(addr.Addr) {
addr = nil
}
m.Lock()
defer m.Unlock()
m.replyTo = addr
return m
}
// Part adds an alternative part to the message. For a plain-text and/or an HTML body use the
// convenience methods: Text, TextTemplate, Html or HtmlTemplate.
func (m *Message) Part(ctype string, cte CTE, bytes []byte, related ...Related) *Message {
m.Lock()
defer m.Unlock()
m.parts = append(m.parts, &part{
ctype: ctype,
cte: cte,
bytes: bytes,
related: related,
})
m.prepared = false // related may include files
return m
}
// Text sets the plain-text version of the message body to the provided content.
func (m *Message) Text(text interface{}) *Message {
m.Lock()
defer m.Unlock()
if m.text == nil {
m.text = &part{}
m.parts = append(m.parts, m.text)
}
switch text := text.(type) {
case string:
*(m.text) = part{
ctype: "text/plain; charset=utf-8",
cte: QuotedPrintable,
bytes: []byte(text),
}
case []byte:
*(m.text) = part{
ctype: "text/plain; charset=utf-8",
cte: QuotedPrintable,
bytes: text,
}
case *ttpl.Template:
*(m.text) = part{
ctype: "text/plain; charset=utf-8",
cte: QuotedPrintable,
tpl: text,
}
default:
m.errors = append(m.errors, errors.New("invalid argument type"))
}
return m
}
// TextTemplate sets the plain-text version of the message body to the provided template.
func (m *Message) TextTemplate(tpl string) *Message {
var (
t *ttpl.Template
err error
)
if tpl != "" {
t, err = ttpl.New("").Parse(tpl)
if err != nil {
m.errors = append(m.errors, errors.New("invalid text template:\n"+tpl+"\nerror: "+err.Error()))
return m
}
}
m.Lock()
defer m.Unlock()
if m.text == nil {
m.text = &part{}
m.parts = append(m.parts, m.text)
}
*(m.text) = part{
ctype: "text/plain; charset=utf-8",
cte: QuotedPrintable,
tpl: t,
}
return m
}
// Html sets the HTML version of the message body to the provided content.
// Optionally, related objects can be specified for inclusion.
func (m *Message) Html(html interface{}, related ...Related) *Message {
m.Lock()
defer m.Unlock()
if m.html == nil {
m.html = &part{}
m.parts = append(m.parts, m.html)
}
switch html := html.(type) {
case string:
*(m.html) = part{
ctype: "text/html; charset=utf-8",
cte: QuotedPrintable,
bytes: []byte(html),
related: related,
}
case []byte:
*(m.html) = part{
ctype: "text/html; charset=utf-8",
cte: QuotedPrintable,
bytes: html,
related: related,
}
case *htpl.Template:
*(m.html) = part{
ctype: "text/html; charset=utf-8",
cte: QuotedPrintable,
htmlTpl: html,
related: related,
}
default:
m.errors = append(m.errors, errors.New("invalid argument type"))
}
m.prepared = false // related may include files
return m
}
// HtmlTemplate sets the HTML version of the message body to the provided template.
// Optionally, related objects can be specified for inclusion.
func (m *Message) HtmlTemplate(tpl string, related ...Related) *Message {
var (
t *htpl.Template
err error
)
if tpl != "" {
t, err = htpl.New("").Parse(tpl)
if err != nil {
m.errors = append(m.errors, errors.New("invalid html template:\n"+tpl+"\nerror: "+err.Error()))
return m
}
}
m.Lock()
defer m.Unlock()
if m.html == nil {
m.html = &part{}
m.parts = append(m.parts, m.html)
}
*(m.html) = part{
ctype: "text/html; charset=utf-8",
cte: QuotedPrintable,
htmlTpl: t,
related: related,
}
m.prepared = false // related may include files
return m
}
// Attach attaches the files provided as filesystem paths.
func (m *Message) Attach(file ...string) *Message {
m.Lock()
defer m.Unlock()
for _, fileName := range file {
m.attachments = append(m.attachments, &attachment{fileName: fileName})
}
m.prepared = false
return m
}
// AttachFile attaches a file specified by its filesystem path, setting its name and type
// to the provided values.
func (m *Message) AttachFile(name, ctype, file string) *Message {
m.Lock()
defer m.Unlock()
m.attachments = append(m.attachments, &attachment{
name: name,
ctype: ctype,
fileName: file,
})
m.prepared = false
return m
}
// AttachObject creates an attachment with the name, type and data provided.
func (m *Message) AttachObject(name, ctype string, data []byte) *Message {
m.Lock()
defer m.Unlock()
m.attachments = append(m.attachments, &attachment{
name: name,
ctype: ctype,
data: data,
})
return m
}
func (m *Message) prepare(force bool) {
if m.prepared && !force {
return
}
allOk := true
for _, p := range m.parts {
for _, r := range p.related {
if r.fileName != "" && (force || len(r.data) == 0) {
if file, err := ioutil.ReadFile(r.fileName); err == nil {
r.data = file
} else {
m.errors = append(m.errors, errors.New("cannot read file: "+r.fileName+": "+err.Error()))
allOk = false
}
}
}
}
for _, a := range m.attachments {
if a.fileName != "" && (force || len(a.data) == 0) {
if file, err := ioutil.ReadFile(a.fileName); err == nil {
a.data = file
if a.name == "" {
a.name = filepath.Base(a.fileName)
}
if a.ctype == "" {
a.ctype = mime.TypeByExtension(filepath.Ext(a.fileName))
}
} else {
m.errors = append(m.errors, errors.New("cannot read file: "+a.fileName+": "+err.Error()))
allOk = false
}
}
}
m.prepared = allOk
}
// Prepare reads all the files referenced by the message at attachments or related items.
//
// If the message was already prepared and no new files have been added, it is no-op.
func (m *Message) Prepare() *Message {
m.Lock()
defer m.Unlock()
m.prepare(false)
return m
}
// PrepareFresh forces a new preparation of the message, even if there were no changes to the referred
// files since the previous one.
func (m *Message) PrepareFresh() *Message {
m.Lock()
defer m.Unlock()
m.prepare(true)
return m
}
// Compose merges the `data` into the receiver's templates and creates the body of the SMTP message
// to be sent.
func (m *Message) Compose(data interface{}) []byte {
m.Lock()
defer m.Unlock()
var (
from *Address
recpts []*Address
buf bytes.Buffer
)
switch {
case m.from != nil:
from = m.from
case m.sender != nil && m.sender.address != nil:
from = m.sender.address
case defaultSender != nil && defaultSender.address != nil:
from = defaultSender.address
}
if from == nil {
m.errors = append(m.errors, errors.New("no From address"))
return []byte{}
}
if m.subjectTpl != nil {
buf.Reset()
if err := m.subjectTpl.Execute(&buf, data); err != nil {
m.errors = append(m.errors, errors.New("failed Execute on subject template: "+err.Error()))
}
m.subject = make([]byte, buf.Len())
copy(m.subject, buf.Bytes())
}
for partNo, partData := range m.parts {
switch {
case partData.tpl != nil:
buf.Reset()
if err := partData.tpl.Execute(&buf, data); err != nil {
m.errors = append(m.errors, errors.New("failed Execute on part["+strconv.Itoa(partNo)+"] template: "+err.Error()))
}
partData.bytes = make([]byte, buf.Len())
copy(partData.bytes, buf.Bytes())
case partData.htmlTpl != nil:
buf.Reset()
if err := partData.htmlTpl.Execute(&buf, data); err != nil {
m.errors = append(m.errors, errors.New("failed Execute on part["+strconv.Itoa(partNo)+"] html template: "+err.Error()))
}
partData.bytes = make([]byte, buf.Len())
copy(partData.bytes, buf.Bytes())
}
}
if len(m.parts) == 0 {
m.errors = append(m.errors, errors.New("message has no parts"))
}
m.prepare(false)
if len(m.errors) != 0 {
return []byte{}
}
domain := m.domain
if len(domain) == 0 {
domain = []byte(from.Domain())
}
ts := []byte(now().In(time.UTC).Format(time.RFC1123Z))
uid := newUUID()
msg := newBuffer(4096)
msg.Write("Message-ID: <", uid, '@', domain, ">\r\n")
msg.Write("Date: ", ts, "\r\n")
msg.Write("Subject: ", QEncodeIfNeeded(m.subject, 9), "\r\n")
addr, _ := from.encode(6)
msg.Write("From: ", addr, "\r\n")
if m.replyTo != nil && m.replyTo.Addr != "" && m.replyTo.Addr != from.Addr {
addr, _ = m.replyTo.encode(10)
msg.Write("Reply-To: ", addr, "\r\n")
}
listAddrs := func(list []*Address, offset int) []byte {
addrs := newBuffer(1024)
for i, item := range list {
if i > 0 {
switch {
case offset < 75:
addrs.Write(", ")
offset += 2
case offset < 76:
addrs.Write(",\r\n ")
offset = 1
default:
addrs.Write("\r\n , ")
offset = 3
}
}
addr, offset = item.encode(offset)
addrs.Write(addr)
}
return addrs.Bytes()
}
recpts = m.to
if len(recpts) == 0 {
recpts = []*Address{from}
}
msg.Write("To: ", listAddrs(recpts, 4), "\r\n")
if len(m.cc) > 0 {
msg.Write("Cc: ", listAddrs(m.cc, 4), "\r\n")
}
// Do not add BCC addresses into the message - they will show up at all recipients!
msg.Write("MIME-Version: 1.0\r\n")
if len(m.attachments) > 0 {
msg.Write("Content-Type: multipart/mixed;\r\n\tboundary=B_m_", uid,
"\r\n\r\n--B_m_", uid, "\r\n")
}
alt := m.html != nil || len(m.parts) > 1
if alt {
msg.Write("Content-Type: multipart/alternative;\r\n\tboundary=B_a_", uid, "\r\n")
}
if m.html != nil && m.text == nil {
if alt {
msg.Write("\r\n--B_a_", uid, "\r\n")
}
msg.Write("Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n",
QuotedPrintableEncode([]byte(htmlToText(string(m.html.bytes)))), "\r\n")
}
for partNo, partData := range m.parts {
if alt {
msg.Write("\r\n--B_a_", uid, "\r\n")
}
pn := strconv.Itoa(partNo)
if len(partData.related) > 0 {
msg.Write("Content-Type: multipart/related;\r\n\tboundary=B_r_", pn, uid,
"\r\n\r\n--B_r_", pn, uid, "\r\n")
// ToDo: substitute the related Ids in content
}
switch partData.cte {
case Base64:
msg.Write("Content-Type: ", partData.ctype, "\r\nContent-Transfer-Encoding: base64\r\n\r\n",
Base64Encode(partData.bytes), "\r\n")
default:
fallthrough
case QuotedPrintable:
msg.Write("Content-Type: ", partData.ctype, "\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n",
QuotedPrintableEncode(partData.bytes), "\r\n")
}
for _, relData := range partData.related {
msg.Write("\r\n--B_r_", pn, uid, "\r\n")
msg.Write("Content-Type: ", relData.ctype, "\r\nContent-Transfer-Encoding: base64\r\n\r\n",
Base64Encode(relData.data), "\r\n")
}
if len(partData.related) > 0 {
msg.Write("\r\n--B_r_", pn, uid, "--\r\n")
}
}
if alt {
msg.Write("\r\n--B_a_", uid, "--\r\n")
}
for _, attData := range m.attachments {
msg.Write("\r\n--B_m_", uid, "\r\n")
msg.Write("Content-Type: ", attData.ctype,
"\r\nContent-Disposition: attachment;\r\n\tfilename=", fmt.Sprintf("%q", attData.name),
"\r\nContent-Transfer-Encoding: base64\r\n\r\n",
Base64Encode(attData.data), "\r\n")
}
if len(m.attachments) > 0 {
msg.Write("\r\n--B_m_", uid, "--\r\n")
}
return msg.Bytes()
}
// FromAddr returns the email address that the message would be sent from.
func (m *Message) FromAddr() string {
m.RLock()
defer m.RUnlock()
var from *Address
switch {
case m.from != nil:
from = m.from
case m.sender != nil && m.sender.address != nil:
from = m.sender.address
case defaultSender != nil && defaultSender.address != nil:
from = defaultSender.address
}
if from != nil {
return from.Addr
}
return ""
}
// RecipientAddrs returns a list of email addresses with all the recipients for the message.
//
// It includes addresses from the To, CC and BCC fields.
func (m *Message) RecipientAddrs() []string {
m.RLock()
defer m.RUnlock()
to := make([]string, 0, len(m.to)+len(m.cc)+len(m.bcc)+1)
seen := map[string]struct{}{}
if len(m.to) == 0 {
addr := m.FromAddr()
to = append(to, addr)
seen[addr] = struct{}{}
}
for _, val := range m.to {
addr := val.Addr
if _, s := seen[addr]; !s {
to = append(to, addr)
seen[addr] = struct{}{}
}
}
for _, val := range m.cc {
addr := val.Addr
if _, s := seen[addr]; !s {
to = append(to, addr)
seen[addr] = struct{}{}
}
}
for _, val := range m.bcc {
addr := val.Addr
if _, s := seen[addr]; !s {
to = append(to, addr)
seen[addr] = struct{}{}
}
}
return to
}
// HasErrors checks if there are any errors associated with the receiver
func (m *Message) HasErrors() bool {
m.RLock()
defer m.RUnlock()
return len(m.errors) > 0
}
// Errors returns the list of errors associated with the receiver, then resets the internal list.
func (m *Message) Errors() (errs []error) {
m.Lock()
defer m.Unlock()
errs, m.errors = m.errors, nil
return
}
// NewMessage creates a new Message, deep-copying from `msg`, if provided.
func NewMessage(msg *Message) *Message {
if msg == nil {
return &Message{prepared: true}
}
msg.RLock()
defer msg.RUnlock()
m := &Message{
domain: msg.domain,
sender: msg.sender,
subject: msg.subject,
subjectTpl: msg.subjectTpl,
from: msg.from.Clone(),
replyTo: msg.replyTo.Clone(),
to: msg.to.Clone(),
cc: msg.cc.Clone(),
bcc: msg.bcc.Clone(),
prepared: msg.prepared,
}
m.parts = make([]*part, len(msg.parts))
for i, partData := range msg.parts {
p := &part{
ctype: partData.ctype,
cte: partData.cte,
tpl: partData.tpl,
htmlTpl: partData.htmlTpl,
// related []Related
}
if len(partData.bytes) > 0 {
p.bytes = make([]byte, len(partData.bytes))
copy(p.bytes, partData.bytes)
}
if len(partData.related) > 0 {
p.related = make([]Related, len(partData.related))
copy(p.related, partData.related)
// do not copy partData.related.data, to save memory; it is never updated in place
}
if msg.text == partData {
m.text = p
}
if msg.html == partData {
m.html = p
}
m.parts[i] = p
}
m.attachments = make([]*attachment, len(msg.attachments))
for i, attData := range msg.attachments {
m.attachments[i] = attData
// do not copy attData.data, to save memory; it is never updated in place
}
return m
}
// QuickMessage creates a Message with the subject and the body provided. Alternative text and HTML
// body versions can be provided, in this order.
func QuickMessage(subject string, body ...string) *Message {
msg := &Message{subject: []byte(subject), prepared: true}
if len(body) > 0 {
msg.Text(body[0])
}
if len(body) > 1 {
msg.Html(body[1])
}
return msg
}
type part struct {
ctype string
cte CTE
bytes []byte
tpl *ttpl.Template
htmlTpl *htpl.Template
related []Related
}
// Related represents a multipart/related item.
type Related struct {
id string
ctype string
fileName string
data []byte
}
// RelatedFile creates a Related structure from the provided file information.
func RelatedFile(id, ctype, file string) Related {
return Related{
id: id,
ctype: ctype,
fileName: file,
}
}
// RelatedObject creates a Related structure from the provided data.
func RelatedObject(id, ctype string, data []byte) Related {
return Related{
id: id,
ctype: ctype,
data: data,
}
}
type attachment struct {
name string
ctype string
fileName string
data []byte
}