2021-12-17 04:54:03 +00:00
|
|
|
package email
|
2021-12-17 03:46:04 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
_ "embed"
|
|
|
|
"html/template"
|
2021-12-24 19:31:53 +00:00
|
|
|
"strings"
|
2021-12-17 03:46:04 +00:00
|
|
|
|
|
|
|
"github.com/vanng822/go-premailer/premailer"
|
|
|
|
"github.com/yuin/goldmark"
|
|
|
|
"github.com/yuin/goldmark/extension"
|
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed base.gohtml
|
|
|
|
var mailTmpl string
|
|
|
|
|
|
|
|
var engine *template.Template
|
|
|
|
var app App
|
|
|
|
|
2021-12-17 04:54:03 +00:00
|
|
|
var mdParser = goldmark.New(
|
|
|
|
goldmark.WithExtensions(extension.GFM),
|
|
|
|
)
|
|
|
|
|
2021-12-17 03:46:04 +00:00
|
|
|
func init() {
|
|
|
|
engine = template.Must(template.New("email").Funcs(template.FuncMap{
|
2021-12-17 04:54:03 +00:00
|
|
|
"ToHTML": ToHTML,
|
2021-12-24 05:31:33 +00:00
|
|
|
"add": func(a, b int) int {
|
|
|
|
return a + b
|
|
|
|
},
|
|
|
|
"mul": func(a, b int) int {
|
|
|
|
return a * b
|
|
|
|
},
|
2021-12-24 19:31:53 +00:00
|
|
|
"replace": func(from, to, input string) string {
|
|
|
|
return strings.Replace(input, from, to, -1)
|
|
|
|
},
|
2021-12-17 03:46:04 +00:00
|
|
|
}).Parse(mailTmpl))
|
|
|
|
}
|
|
|
|
|
2021-12-17 04:54:03 +00:00
|
|
|
func ToHTML(mdtext string) (template.HTML, error) {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
if err := mdParser.Convert([]byte(mdtext), &buf); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return template.HTML(buf.String()), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func Parse(b *Body) (string, error) {
|
2021-12-17 03:46:04 +00:00
|
|
|
b.App = app
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
err := engine.Execute(buf, b)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
pre, err := premailer.NewPremailerFromString(buf.String(), premailer.NewOptions())
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
html, err := pre.Transform()
|
|
|
|
return html, err
|
|
|
|
}
|