forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.go
86 lines (72 loc) · 1.93 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
package mail
import (
"os"
"path/filepath"
"github.com/gobuffalo/buffalo/generators"
"github.com/gobuffalo/buffalo/meta"
"github.com/gobuffalo/makr"
"github.com/gobuffalo/packr"
"github.com/markbates/inflect"
"github.com/pkg/errors"
)
// Generator for creating new mailers
type Generator struct {
App meta.App `json:"app"`
Name inflect.Name `json:"name"`
SkipInit bool `json:"skip_init"`
}
// Run the new mailer generator. It will init the mailers directory
// if it doesn't already exist
func (d Generator) Run(root string, data makr.Data) error {
g := makr.New()
defer g.Fmt(root)
data["opts"] = d
if err := d.initGenerator(data); err != nil {
return errors.WithStack(err)
}
fn := d.Name.File()
g.Add(makr.NewFile(filepath.Join("mailers", fn+".go"), mailerTmpl))
g.Add(makr.NewFile(filepath.Join("templates", "mail", fn+".html"), mailTmpl))
return g.Run(root, data)
}
func (d Generator) initGenerator(data makr.Data) error {
files, err := generators.FindByBox(packr.NewBox("../mail/init/templates"))
if err != nil {
return errors.WithStack(err)
}
g := makr.New()
for _, f := range files {
g.Add(makr.NewFile(f.WritePath, f.Body))
}
g.Should = func(data makr.Data) bool {
if d.SkipInit {
return false
}
if _, err := os.Stat(filepath.Join("mailers", "mailers.go")); err == nil {
return false
}
return true
}
return g.Run(".", data)
}
const mailerTmpl = `package mailers
import (
"github.com/gobuffalo/buffalo/render"
"github.com/gobuffalo/buffalo/mail"
"github.com/pkg/errors"
)
func Send{{.opts.Name.Model}}() error {
m := mail.NewMessage()
// fill in with your stuff:
m.Subject = "{{.opts.Name.Title}}"
m.From = ""
m.To = []string{}
err := m.AddBody(r.HTML("{{.opts.Name.File}}.html"), render.Data{})
if err != nil {
return errors.WithStack(err)
}
return smtp.Send(m)
}
`
const mailTmpl = `<h2>{{.opts.Name.Title}}</h2>
<h3>../templates/mail/{{.opts.Name.File}}.html</h3>`