Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
70 lines
1.7 KiB
Go
70 lines
1.7 KiB
Go
package mail
|
|
|
|
import (
|
|
"bytes"
|
|
"embed"
|
|
"fmt"
|
|
htmltpl "html/template"
|
|
"strings"
|
|
texttpl "text/template"
|
|
)
|
|
|
|
//go:embed templates/*
|
|
var templates embed.FS
|
|
|
|
// Kinds the registry can send.
|
|
const (
|
|
KindDocumentPublished = "document.published"
|
|
KindFindingsNew = "findings.new"
|
|
)
|
|
|
|
// Kinds lists every kind with templates, for validating requests.
|
|
var Kinds = map[string]bool{KindDocumentPublished: true, KindFindingsNew: true}
|
|
|
|
// View is what a template sees.
|
|
type View struct {
|
|
Lang string
|
|
Tenant string
|
|
URL string
|
|
Subject string
|
|
D map[string]any
|
|
}
|
|
|
|
// Render builds the subject, text and HTML body of kind in locale ("de"
|
|
// unless "en"). HTML values are escaped by html/template; the text body and
|
|
// subject are plain.
|
|
func Render(kind, locale string, v View) (Message, error) {
|
|
if !Kinds[kind] {
|
|
return Message{}, fmt.Errorf("mail: unknown kind %q", kind)
|
|
}
|
|
if locale != "en" {
|
|
locale = "de"
|
|
}
|
|
v.Lang = locale
|
|
if v.D == nil {
|
|
v.D = map[string]any{}
|
|
}
|
|
file := "templates/" + locale + "_" + kind + ".tmpl"
|
|
tt, err := texttpl.ParseFS(templates, file)
|
|
if err != nil {
|
|
return Message{}, err
|
|
}
|
|
var subj, text bytes.Buffer
|
|
if err := tt.ExecuteTemplate(&subj, "subject", v); err != nil {
|
|
return Message{}, err
|
|
}
|
|
if err := tt.ExecuteTemplate(&text, "text", v); err != nil {
|
|
return Message{}, err
|
|
}
|
|
v.Subject = strings.Join(strings.Fields(subj.String()), " ")
|
|
ht, err := htmltpl.ParseFS(templates, "templates/layout.html", file)
|
|
if err != nil {
|
|
return Message{}, err
|
|
}
|
|
var html bytes.Buffer
|
|
if err := ht.ExecuteTemplate(&html, "layout", v); err != nil {
|
|
return Message{}, err
|
|
}
|
|
return Message{Subject: v.Subject, Text: strings.TrimSpace(text.String()) + "\n", HTML: html.String()}, nil
|
|
}
|