// SPDX-License-Identifier: AGPL-3.0-or-later // Package mail sends Docwell's own emails (invites, test mails). Delivery goes // through PocketBase (pb_hooks/docwell.pb.js), so every email uses the one SMTP // configuration the admin panel edits. package mail import ( "bytes" "context" "embed" "fmt" "html/template" "net/http" "strings" texttemplate "text/template" "docwell/server/internal/store/pocketbase" ) // 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 } // PBSender sends through PocketBase's mail hook. type PBSender struct{ PB *pocketbase.Client } func (s PBSender) Send(ctx context.Context, m Message) error { return s.PB.Do(ctx, http.MethodPost, "/api/docwell/mail", m, nil) } //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 }