forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
88 lines (71 loc) · 1.89 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
package mail
import (
"io"
"bytes"
"github.com/gobuffalo/buffalo/render"
)
//Message represents an Email message
type Message struct {
From string
To []string
CC []string
Bcc []string
Subject string
Headers map[string]string
Bodies []Body
Attachments []Attachment
}
// Body represents one of the bodies in the Message could be main or alternative
type Body struct {
Content string
ContentType string
}
// Attachment are files added into a email message
type Attachment struct {
Name string
Reader io.Reader
ContentType string
}
// AddBody the message by receiving a renderer and rendering data, first message will be
// used as the main message Body rest of them will be passed as alternative bodies on the
// email message
func (m *Message) AddBody(r render.Renderer, data render.Data) error {
buf := bytes.NewBuffer([]byte{})
err := r.Render(buf, data)
if err != nil {
return err
}
m.Bodies = append(m.Bodies, Body{
Content: string(buf.Bytes()),
ContentType: r.ContentType(),
})
return nil
}
// AddBodies Allows to add multiple bodies to the message, it returns errors that
// could happen in the rendering.
func (m *Message) AddBodies(data render.Data, renderers ...render.Renderer) error {
for _, r := range renderers {
err := m.AddBody(r, data)
if err != nil {
return err
}
}
return nil
}
//AddAttachment adds the attachment to the list of attachments the Message has.
func (m *Message) AddAttachment(name, contentType string, r io.Reader) error {
m.Attachments = append(m.Attachments, Attachment{
Name: name,
ContentType: contentType,
Reader: r,
})
return nil
}
// SetHeader sets the heder field and value for the message
func (m *Message) SetHeader(field, value string) {
m.Headers[field] = value
}
//NewMessage Builds a new message.
func NewMessage() Message {
return Message{Headers: map[string]string{}}
}