// 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) { var text, html bytes.Buffer if err := textTemplates.ExecuteTemplate(&text, name+".txt", data); err != nil { return Message{}, fmt.Errorf("mail: %s.txt: %w", name, err) } if err := htmlTemplates.ExecuteTemplate(&html, name+".html", data); err != nil { return Message{}, fmt.Errorf("mail: %s.html: %w", name, 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 }