-
Notifications
You must be signed in to change notification settings - Fork 4
/
mail.go
108 lines (87 loc) · 2.36 KB
/
mail.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
package mail
import (
"fmt"
nmail "net/mail"
)
type Mail struct {
FromName, FromAddress string
ToName, ToAddress string
Subject string
templates *Templates
templateName string
templateVars Vars
renderSuccess bool // TODO should we add mutex for it?
HTML, Text []byte
}
func New() *Mail {
return &Mail{}
}
func (m *Mail) From(name, address string) {
m.FromName = name
m.FromAddress = address
}
func (m *Mail) To(name, address string) {
m.ToName = name
m.ToAddress = address
}
func (m *Mail) FromStr() string {
a := nmail.Address{Name: m.FromName, Address: m.FromAddress}
return a.String()
}
func (m *Mail) ToStr() string {
a := nmail.Address{Name: m.ToName, Address: m.ToAddress}
return a.String()
}
// Template sets the template to be used for this email. Make sure to call
// mail.Render() afterwards.
// If both name.html and name.txt are available, both will be included in mail.
// If only name.html or name.txt are available, the one available will be used.
// If neither name.html nor name.txt are available, an error is returned when Rendered.
func (m *Mail) Template(t *Templates, name string, vars Vars) {
if t == nil {
panic("mail.Template: t cannot be nil")
}
m.templates = t
m.templateName = name
m.templateVars = vars
m.renderSuccess = false
}
// Render renders HTML and/or Text portion of email with given Template.
func (m *Mail) Render() error {
if m.renderSuccess {
return nil
}
// make subject available as var in template
m.templateVars["Subject"] = m.Subject
htmlExists := false
if m.templates.engine.Exists(m.templateName + "." + HTMLExtension) {
htmlExists = true
}
textExists := false
if m.templates.engine.Exists(m.templateName + "." + TextExtension) {
textExists = true
}
if !htmlExists && !textExists {
return fmt.Errorf("neither '%v.%v' nor '%v.%v' could be found", m.templateName, HTMLExtension, m.templateName, TextExtension)
}
var err error
if htmlExists {
m.HTML, err = m.templates.Render(m.templateName+"."+HTMLExtension, m.templateVars)
if err != nil {
return err
}
}
if textExists {
m.Text, err = m.templates.Render(m.templateName+"."+TextExtension, m.templateVars)
if err != nil {
return err
}
}
// HTML and/or Text successfully rendered
m.renderSuccess = true
// remove reference to allow G
m.templates = nil
m.templateName = ""
m.templateVars = nil
return nil
}