// Branded HTML rendering for transactional email. template.html is the // Superbrain email design (table layout, Outlook VML button fallback, // dark-mode overrides); it is embedded verbatim and filled here. // // The template uses {{placeholder}} markers rather than text/template so // the design file stays editable as plain HTML (and Outlook conditional // comments survive untouched). Every substituted value is HTML-escaped, // and optional sections (CTA button + fallback link, note block, footer // links, address line) are removed when their values are empty. package mailer import ( _ "embed" "errors" "fmt" "html" "strings" ) //go:embed template.html var emailTemplate string // Content describes one branded rendering. Headline falls back to the // subject, SignOff to "Thanks,", CTALabel to "Open Superbrain", and the // preheader to the first body paragraph. Empty optional fields remove // their section instead of rendering a stub. type Content struct { Preheader string // inbox preview line (kept under ~90 characters) Headline string FirstName string // optional; the greeting degrades to "Hi," Body string // newline-separated paragraphs CTAURL string // optional button + fallback link CTALabel string Note string // optional highlighted note block SignOff string // Optional footer links; unset ones are omitted. PreferencesURL string UnsubscribeURL string HelpURL string CompanyAddress string // UnsubscribePostURL is the RFC 8058 one-click endpoint (POST, token in // the query). When set, the message carries List-Unsubscribe + // List-Unsubscribe-Post headers so mail clients can offer native // unsubscribe. It is independent of UnsubscribeURL (the human page). UnsubscribePostURL string } // Template markers. The CTA cut spans the button row AND the fallback-link // row (both are meaningless without a URL); the note cut spans the optional // note block. Anchors must stay in sync with template.html — Render errors // (and the unit tests fail) if the design drifts away from them. const ( ctaStartMarker = "" noteStartMarker = "" bodyStartAnchor = `

{{body_paragraph_1}}

` bodyEndAnchor = `

{{body_paragraph_2}}

` addressParagraph = `

Superbrain, {{company_address}}

` footerLinkAnchor = "{{preferences_url}}" ) // Render fills the embedded template for one message. An error means the // template no longer matches the renderer's anchors (a programming error, // caught by tests); callers degrade to plain text rather than block mail. func Render(subject string, c Content) (string, error) { s := emailTemplate var err error headline := c.Headline if headline == "" { headline = subject } paras := paragraphs(c.Body) preheader := c.Preheader if preheader == "" && len(paras) > 0 { preheader = paras[0] } if preheader == "" { preheader = headline } preheader = truncateRunes(preheader, 90) // Optional CTA: without a URL, drop the button and fallback-link rows. if c.CTAURL == "" { s, err = cutSpan(s, ctaStartMarker, noteStartMarker) if err != nil { return "", err } } else { label := c.CTALabel if label == "" { label = "Open Superbrain" } s = strings.ReplaceAll(s, "{{cta_url}}", html.EscapeString(c.CTAURL)) s = strings.ReplaceAll(s, "{{cta_label}}", html.EscapeString(label)) } // Optional note block. if c.Note == "" { s, err = cutSpan(s, noteStartMarker, signOffMarker) if err != nil { return "", err } } else { s = strings.ReplaceAll(s, "{{note_text}}", html.EscapeString(c.Note)) } // Greeting: a missing name must not render "Hi ,". greeting := "Hi," if c.FirstName != "" { greeting = "Hi " + html.EscapeString(c.FirstName) + "," } s = strings.Replace(s, "Hi {{first_name}},", greeting, 1) // Body: replace the two placeholder paragraphs with one

per line. var b strings.Builder for i, p := range paras { style := "margin:0 0 16px 0;" if i == len(paras)-1 { style = "margin:0;" } if i > 0 { b.WriteString("\n ") } b.WriteString(`

` + html.EscapeString(p) + `

`) } s, err = replaceSpan(s, bodyStartAnchor, bodyEndAnchor, b.String()) if err != nil { return "", err } signOff := c.SignOff if signOff == "" { signOff = "Thanks," } s = strings.ReplaceAll(s, "{{sign_off}}", html.EscapeString(signOff)) s = strings.ReplaceAll(s, "{{subject}}", html.EscapeString(subject)) s = strings.ReplaceAll(s, "{{preheader_text}}", html.EscapeString(preheader)) s = strings.ReplaceAll(s, "{{headline}}", html.EscapeString(headline)) // Footer links: keep only the ones with a URL; drop the whole paragraph // when none are configured (the product has no preference/help pages yet). s, err = renderFooterLinks(s, c) if err != nil { return "", err } if c.CompanyAddress == "" { s = strings.Replace(s, addressParagraph, "", 1) } else { s = strings.ReplaceAll(s, "{{company_address}}", html.EscapeString(c.CompanyAddress)) } if strings.Contains(s, "{{") { return "", errors.New("mailer: template has unfilled placeholders") } return s, nil } func renderFooterLinks(s string, c Content) (string, error) { var links []string for _, l := range []struct{ url, label string }{ {c.PreferencesURL, "Email preferences"}, {c.UnsubscribeURL, "Unsubscribe"}, {c.HelpURL, "Help center"}, } { if l.url == "" { continue } links = append(links, ``+l.label+``) } start, end, err := paragraphSpan(s, footerLinkAnchor) if err != nil { return "", err } if len(links) == 0 { return s[:start] + s[end:], nil } repl := `

` + strings.Join(links, "  |  ") + `

` return s[:start] + repl + s[end:], nil } // paragraphs splits body text into trimmed, non-empty lines. func paragraphs(body string) []string { var out []string for _, line := range strings.Split(body, "\n") { if line = strings.TrimSpace(line); line != "" { out = append(out, line) } } return out } func truncateRunes(s string, n int) string { r := []rune(s) if len(r) <= n { return s } return string(r[:n]) } // cutSpan removes [startMarker, endMarker) — the end marker stays for the // next cut. Both markers must exist. func cutSpan(s, startMarker, endMarker string) (string, error) { i := strings.Index(s, startMarker) if i < 0 { return "", fmt.Errorf("mailer: template marker %q not found", startMarker) } j := strings.Index(s[i:], endMarker) if j < 0 { return "", fmt.Errorf("mailer: template marker %q not found", endMarker) } return s[:i] + s[i+j:], nil } // replaceSpan swaps [startAnchor, endAnchor] (inclusive) for repl. func replaceSpan(s, startAnchor, endAnchor, repl string) (string, error) { i := strings.Index(s, startAnchor) if i < 0 { return "", fmt.Errorf("mailer: template anchor %q not found", startAnchor) } j := strings.Index(s[i:], endAnchor) if j < 0 { return "", fmt.Errorf("mailer: template anchor %q not found", endAnchor) } return s[:i] + repl + s[i+j+len(endAnchor):], nil } // paragraphSpan locates the

…

enclosing anchor. func paragraphSpan(s, anchor string) (start, end int, err error) { i := strings.Index(s, anchor) if i < 0 { return 0, 0, fmt.Errorf("mailer: template anchor %q not found", anchor) } start = strings.LastIndex(s[:i], "") if start < 0 || j < 0 { return 0, 0, errors.New("mailer: template paragraph around anchor not found") } return start, i + j + len("

"), nil }