// SPDX-License-Identifier: AGPL-3.0-or-later // Package mail sends Docwell's own emails (invites, notifications, test // mails). They go out over SMTP with the same mail server configuration // PocketBase uses for its auth emails (see SMTPSender). package mail import ( "bytes" "context" "embed" "fmt" "html/template" "strings" texttemplate "text/template" ) // Message is one email. HTML and Text are alternative bodies. type Message struct { To string `json:"to"` Subject string `json:"subject"` HTML string `json:"html"` Text string `json:"text"` } // Sender delivers a message. type Sender interface { Send(ctx context.Context, m Message) error } //go:embed templates var files embed.FS var ( htmlTemplates = template.Must(template.ParseFS(files, "templates/*.html")) textTemplates = texttemplate.Must(texttemplate.ParseFS(files, "templates/*.txt")) ) // Render builds a message from the templates named name.html and name.txt. // The first line of the text template is the subject. func Render(to, name string, data any) (Message, error) { return RenderIn("", to, name, data) } // RenderIn is Render in a language: from name..html and // name..txt when there are such templates, else the English ones. func RenderIn(lang, to, name string, data any) (Message, error) { textName, htmlName := name+".txt", name+".html" if lang != "" && textTemplates.Lookup(name+"."+lang+".txt") != nil && htmlTemplates.Lookup(name+"."+lang+".html") != nil { textName, htmlName = name+"."+lang+".txt", name+"."+lang+".html" } var text, html bytes.Buffer if err := textTemplates.ExecuteTemplate(&text, textName, data); err != nil { return Message{}, fmt.Errorf("mail: %s: %w", textName, err) } if err := htmlTemplates.ExecuteTemplate(&html, htmlName, data); err != nil { return Message{}, fmt.Errorf("mail: %s: %w", htmlName, err) } subject, body, _ := strings.Cut(text.String(), "\n") return Message{To: to, Subject: strings.TrimSpace(subject), HTML: html.String(), Text: strings.TrimSpace(body) + "\n"}, nil }