The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
feat: HTML email template for notification/alert emails (#294)
Jovan Stojiljkovic2baeb98806d2
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8279cf35..c4b1e732 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1212,6 +1212,16 @@ if err != nil {- **Validation errors** (user-facing): `c.JSON(422, gin.H{"error": "message"})` for form validation- **Always** wrap errors with `traceway.NewStackTraceErrorf` or `fmt.Errorf` using `%w` — never discard the original error+### Notification Email Templates (HTML)++Notification/alert/monitor emails are sent as styled HTML through one shared layout; only the email adapter renders HTML, every other channel stays plaintext.++- **`backend/app/services/emailtemplate/`** — the layout (`base.gohtml`, embedded via `go:embed`, parsed once with `template.Must`) and `Render(Data)`. `Data` fields: `Title`, `Badge`/`BadgeColor` (severity chip; `ColorCritical`/`ColorWarning`/`ColorInfo`), `Paragraphs` (internal `\n` becomes `<br>` via the `nl2br` func), `Details` (label/value rows, monospace values), `CodeBlock` (stack traces, probe errors), `Button` (always the dashboard's outline style — white background, `#d1d9e0` border; severity never colors the button, only the badge), `FooterNote`, `LogoURL` (`LogoURL(baseURL)` = `{APP_BASE_URL}/traceway-mark.png`), `Preheader` (defaults to the first paragraph). Table-based markup with inline styles for Gmail/Outlook; all content is escaped by `html/template`.+- **`emailtemplate.BuildMIME(from, to, subject, textBody, htmlBody)`** — composes `multipart/alternative` (plaintext part first, then HTML), quoted-printable both parts, RFC 2047 subject. Empty `htmlBody` yields a single-part plaintext message. Used by the notifications email adapter; the invitation/password-reset emails in `services/email.service.go` are deliberately still plaintext.+- **Structured message fields** (`models.NotificationMessage`): optional `Intro`, `Details []NotificationMessageDetail`, `CodeBlock`, `ActionLabel`, all `json:",omitempty"`. When any of `Intro`/`Details`/`CodeBlock` is set, `renderMessageHTML` in `adapter_email.go` renders them instead of `Body`; otherwise `Body` is split into paragraphs on blank lines. `Body` must therefore always stay complete on its own — Slack/Telegram/SMS/webhook and `fired_notifications` only ever see `Body`. The fields round-trip through the outbox (the whole `Message` is persisted as JSON), so no migration is needed when adding more; rows enqueued before an upgrade fall back to the generic rendering.+- **Buttons/links**: relative `msg.URL`s are absolutized against `services.EmailService.BaseURL()`; `ActionLabel` overrides the default "View in Traceway" (builders use "View Issue", "View Monitor", "Acknowledge Page"). `msg.HTMLBody`, when set, bypasses the template entirely.+- **Adding a new rule type's email**: nothing to do for a plain sentence (generic path). For richer emails, set `Intro`/`Details`/`CodeBlock`/`ActionLabel` on the `Message` in `messages.go` while keeping `Body` self-contained (see `buildNewErrorMessage` / `buildCheckDownMessage`).+---## Native `/api/report` Protocoldiff --git a/backend/app/models/notification_message.model.go b/backend/app/models/notification_message.model.goindex 4f9e1982..0e3992f3 100644--- a/backend/app/models/notification_message.model.go+++ b/backend/app/models/notification_message.model.go@@ -21,6 +21,15 @@ type NotificationMessage struct {URL stringEndpoint string+ // Optional structured presentation for HTML-capable adapters (email).+ // When any of Intro/Details/CodeBlock is set, the email adapter renders+ // them instead of the plaintext Body; every other adapter keeps using+ // Body, so builders must keep Body complete on its own.+ Intro string `json:",omitempty"`+ Details []NotificationMessageDetail `json:",omitempty"`+ CodeBlock string `json:",omitempty"`+ ActionLabel string `json:",omitempty"`+// DedupToken is the stable identity of what fired within the rule// (exception hash, endpoint, task or metric name; empty for rule-level// conditions). Page dedup keys are built from it — never from URL, which@@ -28,3 +37,10 @@ type NotificationMessage struct {// only matters at page-open time.DedupToken string `json:"-"`}++// NotificationMessageDetail is one label/value row rendered as a details+// table in HTML emails (exception id, hash, server, ...).+type NotificationMessageDetail struct {+ Label string+ Value string+}diff --git a/backend/app/notifications/adapter_email.go b/backend/app/notifications/adapter_email.goindex e8f85c0f..cc3d1fa5 100644--- a/backend/app/notifications/adapter_email.go+++ b/backend/app/notifications/adapter_email.go@@ -11,6 +11,7 @@ import ("github.com/tracewayapp/traceway/backend/app/config""github.com/tracewayapp/traceway/backend/app/services"+ "github.com/tracewayapp/traceway/backend/app/services/emailtemplate")const smtpTimeout = 10 * time.Second@@ -61,13 +62,77 @@ func (a *EmailAdapter) Send(ctx context.Context, msg Message) error {cfg := config.Configfrom := cfg.SMTPFrom- auth := smtp.PlainAuth("", cfg.SMTPUsername, cfg.SMTPPassword, cfg.SMTPHost)+ // No username means an auth-less relay; smtp.PlainAuth would refuse to+ // run over an unencrypted connection anyway.+ var auth smtp.Auth+ if cfg.SMTPUsername != "" {+ auth = smtp.PlainAuth("", cfg.SMTPUsername, cfg.SMTPPassword, cfg.SMTPHost)+ }addr := fmt.Sprintf("%s:%s", cfg.SMTPHost, cfg.SMTPPort)- emailMsg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s",- from, strings.Join(a.Recipients, ", "), subject, msg.Body)+ htmlBody := msg.HTMLBody+ if htmlBody == "" {+ var err error+ htmlBody, err = renderMessageHTML(msg, emailSvc.BaseURL())+ if err != nil {+ return fmt.Errorf("failed to render email HTML: %w", err)+ }+ }+ emailMsg, err := emailtemplate.BuildMIME(from, a.Recipients, subject, msg.Body, htmlBody)+ if err != nil {+ return fmt.Errorf("failed to build email message: %w", err)+ }++ return sendMailWithTimeout(ctx, addr, auth, from, a.Recipients, emailMsg)+}++// renderMessageHTML renders any notification Message through the shared email+// layout. Structured fields (Intro/Details/CodeBlock) win over the plaintext+// Body, which stays the source for every text-only adapter.+func renderMessageHTML(msg Message, baseURL string) (string, error) {+ d := emailtemplate.Data{+ LogoURL: emailtemplate.LogoURL(baseURL),+ Title: msg.Subject,+ }++ switch msg.Severity {+ case SeverityCritical:+ d.Badge, d.BadgeColor = "CRITICAL", emailtemplate.ColorCritical+ case SeverityWarning:+ d.Badge, d.BadgeColor = "WARNING", emailtemplate.ColorWarning+ case SeverityInfo:+ d.Badge, d.BadgeColor = "INFO", emailtemplate.ColorInfo+ }++ if msg.Intro != "" || len(msg.Details) > 0 || msg.CodeBlock != "" {+ if msg.Intro != "" {+ d.Paragraphs = []string{msg.Intro}+ }+ for _, det := range msg.Details {+ d.Details = append(d.Details, emailtemplate.Detail{Label: det.Label, Value: det.Value})+ }+ d.CodeBlock = msg.CodeBlock+ } else if body := strings.TrimSpace(msg.Body); body != "" {+ d.Paragraphs = strings.Split(body, "\n\n")+ }++ if msg.URL != "" {+ u := msg.URL+ if strings.HasPrefix(u, "/") {+ u = strings.TrimRight(baseURL, "/") + u+ }+ label := msg.ActionLabel+ if label == "" {+ label = "View in Traceway"+ }+ d.Button = &emailtemplate.Button{Label: label, URL: u}+ }++ if msg.RuleName != "" {+ d.FooterNote = fmt.Sprintf("You are receiving this because the notification rule %q fired.", msg.RuleName)+ }- return sendMailWithTimeout(ctx, addr, auth, from, a.Recipients, []byte(emailMsg))+ return emailtemplate.Render(d)}func sendMailWithTimeout(ctx context.Context, addr string, auth smtp.Auth, from string, to []string, msg []byte) error {diff --git a/backend/app/notifications/messages.go b/backend/app/notifications/messages.goindex 6e4513d1..8687663e 100644--- a/backend/app/notifications/messages.go+++ b/backend/app/notifications/messages.go@@ -252,25 +252,74 @@ func (d ExceptionDetails) endpointForMessage() string {}func buildNewErrorMessage(details ExceptionDetails, projectName string) Message {+ headline := "A new error has been detected: " + details.ErrorTypereturn Message{- Subject: fmt.Sprintf("[%s] New error: %s", projectName, details.ErrorType),- Body: buildExceptionBody("A new error has been detected: "+details.ErrorType, details),- Severity: SeverityCritical,- URL: fmt.Sprintf("/issues/%s", details.Hash),- Endpoint: details.endpointForMessage(),- DedupToken: details.Hash,+ Subject: fmt.Sprintf("[%s] New error: %s", projectName, details.ErrorType),+ Body: buildExceptionBody(headline, details),+ Severity: SeverityCritical,+ URL: fmt.Sprintf("/issues/%s", details.Hash),+ Endpoint: details.endpointForMessage(),+ DedupToken: details.Hash,+ Intro: headline,+ Details: exceptionMessageDetails(details),+ CodeBlock: details.StackTrace,+ ActionLabel: "View Issue",}}func buildErrorRegressionMessage(details ExceptionDetails, projectName string) Message {+ headline := "A previously resolved error has reappeared: " + details.ErrorTypereturn Message{- Subject: fmt.Sprintf("[%s] Resolved error reappeared: %s", projectName, details.ErrorType),- Body: buildExceptionBody("A previously resolved error has reappeared: "+details.ErrorType, details),- Severity: SeverityCritical,- URL: fmt.Sprintf("/issues/%s", details.Hash),- Endpoint: details.endpointForMessage(),- DedupToken: details.Hash,+ Subject: fmt.Sprintf("[%s] Resolved error reappeared: %s", projectName, details.ErrorType),+ Body: buildExceptionBody(headline, details),+ Severity: SeverityCritical,+ URL: fmt.Sprintf("/issues/%s", details.Hash),+ Endpoint: details.endpointForMessage(),+ DedupToken: details.Hash,+ Intro: headline,+ Details: exceptionMessageDetails(details),+ CodeBlock: details.StackTrace,+ ActionLabel: "View Issue",+ }+}++// exceptionMessageDetails mirrors the detail lines of buildExceptionBody as+// structured rows for the HTML email layout.+func exceptionMessageDetails(d ExceptionDetails) []models.NotificationMessageDetail {+ var rows []models.NotificationMessageDetail+ add := func(label, value string) {+ if value != "" {+ rows = append(rows, models.NotificationMessageDetail{Label: label, Value: value})+ }+ }+ add("Exception ID", d.Id)+ add("Hash", d.Hash)+ if !d.RecordedAt.IsZero() {+ add("Occurred at", d.RecordedAt.UTC().Format("2006-01-02 15:04:05 UTC"))+ }+ add("App version", d.AppVersion)+ add("Server", d.ServerName)+ if d.TraceName != "" {+ switch d.TraceType {+ case "task":+ add("Task", d.TraceName)+ case "ai_trace":+ add("AI trace", d.TraceName)+ default:+ add("Endpoint", d.TraceName)+ }}+ if len(d.Attributes) > 0 {+ keys := make([]string, 0, len(d.Attributes))+ for k := range d.Attributes {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ for _, k := range keys {+ add(k, d.Attributes[k])+ }+ }+ return rows}func buildExceptionBody(headline string, d ExceptionDetails) string {@@ -328,25 +377,30 @@ func buildExceptionBody(headline string, d ExceptionDetails) string {}func buildCheckDownMessage(check *models.SyntheticCheck, errorMsg string, projectName string) Message {- body := fmt.Sprintf("The synthetic check %q is failing (%d consecutive failures).", check.Name, check.ConsecutiveFailures)+ intro := fmt.Sprintf("The synthetic check %q is failing (%d consecutive failures).", check.Name, check.ConsecutiveFailures)+ body := introif errorMsg != "" {body += "\n\nLast error: " + errorMsg}return Message{- Subject: fmt.Sprintf("[%s] Check %q is down", projectName, check.Name),- Body: body,- Severity: SeverityCritical,- URL: fmt.Sprintf("/monitors/%d", check.Id),- DedupToken: fmt.Sprintf("check:%d", check.Id),+ Subject: fmt.Sprintf("[%s] Check %q is down", projectName, check.Name),+ Body: body,+ Severity: SeverityCritical,+ URL: fmt.Sprintf("/monitors/%d", check.Id),+ DedupToken: fmt.Sprintf("check:%d", check.Id),+ Intro: intro,+ CodeBlock: errorMsg,+ ActionLabel: "View Monitor",}}func buildCheckRecoveredMessage(check *models.SyntheticCheck, projectName string) Message {return Message{- Subject: fmt.Sprintf("[%s] Check %q recovered", projectName, check.Name),- Body: fmt.Sprintf("The synthetic check %q is passing again.", check.Name),- Severity: SeverityInfo,- URL: fmt.Sprintf("/monitors/%d", check.Id),- DedupToken: fmt.Sprintf("check:%d", check.Id),+ Subject: fmt.Sprintf("[%s] Check %q recovered", projectName, check.Name),+ Body: fmt.Sprintf("The synthetic check %q is passing again.", check.Name),+ Severity: SeverityInfo,+ URL: fmt.Sprintf("/monitors/%d", check.Id),+ DedupToken: fmt.Sprintf("check:%d", check.Id),+ ActionLabel: "View Monitor",}}diff --git a/backend/app/oncall/escalator.go b/backend/app/oncall/escalator.goindex 2392b01c..ec83c62a 100644--- a/backend/app/oncall/escalator.go+++ b/backend/app/oncall/escalator.go@@ -534,7 +534,7 @@ func claimChannelDelivery(tx *sql.Tx, page *models.Page, level int, channelId infunc buildPageMessage(page *models.Page, level int, ackURL string) notifications.Message {prefix := "[Page] "if level > 0 {- prefix = fmt.Sprintf("[Page — escalation L%d] ", level+1)+ prefix = fmt.Sprintf("[Page - escalation L%d] ", level+1)}body := page.Bodyif body != "" {@@ -547,12 +547,13 @@ func buildPageMessage(page *models.Page, level int, ackURL string) notificationsseverity = notifications.SeverityCritical}return notifications.Message{- Subject: prefix + page.Subject,- Body: body,- Severity: severity,- RuleType: page.RuleType,- RuleName: page.RuleName,- URL: ackURL,+ Subject: prefix + page.Subject,+ Body: body,+ Severity: severity,+ RuleType: page.RuleType,+ RuleName: page.RuleName,+ URL: ackURL,+ ActionLabel: "Acknowledge Page",}}diff --git a/backend/app/services/email.service.go b/backend/app/services/email.service.goindex 74097019..1ed11ca1 100644--- a/backend/app/services/email.service.go+++ b/backend/app/services/email.service.go@@ -95,6 +95,12 @@ func (e *emailService) IsEnabled() bool {return e.enabled}+// BaseURL is the dashboard origin used to absolutize links and reference the+// logo in HTML notification emails.+func (e *emailService) BaseURL() string {+ return e.baseUrl+}+func (e *emailService) SendPasswordReset(toEmail string, token string) error {resetUrl := fmt.Sprintf("%s/reset-password?token=%s", e.baseUrl, token)@@ -134,7 +140,10 @@ The Traceway Teamfunc (e *emailService) sendMail(to []string, msg []byte) error {addr := net.JoinHostPort(e.host, strconv.Itoa(e.port))- auth := smtp.PlainAuth("", e.username, e.password, e.host)+ var auth smtp.Auth+ if e.username != "" {+ auth = smtp.PlainAuth("", e.username, e.password, e.host)+ }conn, err := net.DialTimeout("tcp", addr, 10*time.Second)if err != nil {@@ -157,8 +166,10 @@ func (e *emailService) sendMail(to []string, msg []byte) error {}}- if err := client.Auth(auth); err != nil {- return fmt.Errorf("SMTP auth failed: %w", err)+ if auth != nil {+ if err := client.Auth(auth); err != nil {+ return fmt.Errorf("SMTP auth failed: %w", err)+ }}if err := client.Mail(e.from); err != nil {return fmt.Errorf("SMTP MAIL failed: %w", err)diff --git a/backend/app/services/emailtemplate/base.gohtml b/backend/app/services/emailtemplate/base.gohtmlnew file mode 100644index 00000000..add71bca--- /dev/null+++ b/backend/app/services/emailtemplate/base.gohtml@@ -0,0 +1,64 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>{{.Title}}</title>+</head>+<body style="margin:0;padding:0;background-color:#f6f8fa;">+{{if .Preheader}}<div style="display:none;max-height:0;overflow:hidden;mso-hide:all;">{{.Preheader}}</div>{{end}}+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f6f8fa;">+<tr><td align="center" style="padding:24px 16px;">+<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;">+{{if .LogoURL}}+<tr><td align="center" style="padding:16px 0;">+<img src="{{.LogoURL}}" alt="Traceway" width="36" height="36" style="display:block;border:0;">+</td></tr>+{{end}}+<tr><td align="center" style="padding:0 8px 24px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;font-size:22px;line-height:30px;font-weight:600;color:#1f2328;">{{.Title}}</td></tr>+<tr><td style="background-color:#ffffff;border:1px solid #d1d9e0;border-radius:8px;padding:24px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;font-size:14px;line-height:21px;color:#1f2328;">+{{if .Badge}}+<div style="margin:0 0 16px;"><span style="display:inline-block;padding:2px 10px;border-radius:12px;font-size:11px;font-weight:600;letter-spacing:0.5px;color:#ffffff;background-color:{{.BadgeColor}};">{{.Badge}}</span></div>+{{end}}+{{range .Paragraphs}}+<p style="margin:0 0 16px;">{{. | nl2br}}</p>+{{end}}+{{if .Details}}+<table role="presentation" cellpadding="0" cellspacing="0" style="margin:0 0 16px;">+{{range .Details}}+<tr>+<td style="padding:3px 16px 3px 0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;font-size:13px;line-height:20px;color:#59636e;white-space:nowrap;vertical-align:top;">{{.Label}}</td>+<td style="padding:3px 0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px;line-height:20px;color:#1f2328;word-break:break-all;">{{.Value}}</td>+</tr>+{{end}}+</table>+{{end}}+{{if .CodeBlock}}+<pre style="margin:0 0 16px;padding:12px;background-color:#f6f8fa;border:1px solid #d1d9e0;border-radius:6px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;line-height:18px;color:#1f2328;white-space:pre-wrap;word-break:break-word;">{{.CodeBlock}}</pre>+{{end}}+{{if .Button}}+<table role="presentation" cellpadding="0" cellspacing="0" align="center" style="margin:20px auto 4px;">+<tr><td align="center" style="border:1px solid #d1d9e0;border-radius:6px;background-color:#ffffff;">+<a href="{{.Button.URL}}" style="display:inline-block;padding:10px 24px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;font-size:14px;font-weight:500;color:#1f2328;text-decoration:none;border-radius:6px;">{{.Button.Label}}</a>+</td></tr>+</table>+{{end}}+</td></tr>+{{if .Button}}+<tr><td align="center" style="padding:24px 8px 0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;font-size:13px;line-height:20px;color:#59636e;">+Button not working? Paste the following link into your browser:<br>+<a href="{{.Button.URL}}" style="color:#0969da;text-decoration:none;word-break:break-all;">{{.Button.URL}}</a>+</td></tr>+{{end}}+<tr><td style="padding:24px 0 0;">+<table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr><td style="border-top:1px solid #d1d9e0;font-size:0;line-height:0;"> </td></tr></table>+</td></tr>+<tr><td align="center" style="padding:8px 8px 32px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;font-size:12px;line-height:18px;color:#59636e;">+{{if .FooterNote}}{{.FooterNote}}<br>{{end}}+Traceway · Error tracking & monitoring+</td></tr>+</table>+</td></tr>+</table>+</body>+</html>diff --git a/backend/app/services/emailtemplate/mime.go b/backend/app/services/emailtemplate/mime.gonew file mode 100644index 00000000..5a200a4a--- /dev/null+++ b/backend/app/services/emailtemplate/mime.go@@ -0,0 +1,69 @@+package emailtemplate++import (+ "bytes"+ "fmt"+ "io"+ "mime"+ "mime/multipart"+ "mime/quotedprintable"+ "strings"+ "time"+)++// BuildMIME composes a multipart/alternative message carrying both the+// plaintext and the rendered HTML body, quoted-printable encoded so long+// stack-trace and markup lines stay within SMTP line limits. An empty+// htmlBody yields a plain single-part message.+func BuildMIME(from string, to []string, subject, textBody, htmlBody string) ([]byte, error) {+ var buf bytes.Buffer++ fmt.Fprintf(&buf, "From: %s\r\n", from)+ fmt.Fprintf(&buf, "To: %s\r\n", strings.Join(to, ", "))+ fmt.Fprintf(&buf, "Subject: %s\r\n", mime.QEncoding.Encode("utf-8", subject))+ fmt.Fprintf(&buf, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))+ buf.WriteString("MIME-Version: 1.0\r\n")++ if htmlBody == "" {+ buf.WriteString("Content-Type: text/plain; charset=utf-8\r\n")+ buf.WriteString("Content-Transfer-Encoding: quoted-printable\r\n\r\n")+ if err := writeQuotedPrintable(&buf, textBody); err != nil {+ return nil, err+ }+ return buf.Bytes(), nil+ }++ mw := multipart.NewWriter(&buf)+ fmt.Fprintf(&buf, "Content-Type: multipart/alternative; boundary=%q\r\n\r\n", mw.Boundary())++ for _, part := range []struct {+ contentType string+ body string+ }{+ {"text/plain; charset=utf-8", textBody},+ {"text/html; charset=utf-8", htmlBody},+ } {+ pw, err := mw.CreatePart(map[string][]string{+ "Content-Type": {part.contentType},+ "Content-Transfer-Encoding": {"quoted-printable"},+ })+ if err != nil {+ return nil, err+ }+ if err := writeQuotedPrintable(pw, part.body); err != nil {+ return nil, err+ }+ }+ if err := mw.Close(); err != nil {+ return nil, err+ }+ return buf.Bytes(), nil+}++func writeQuotedPrintable(w io.Writer, body string) error {+ qp := quotedprintable.NewWriter(w)+ if _, err := qp.Write([]byte(body)); err != nil {+ return err+ }+ return qp.Close()+}diff --git a/backend/app/services/emailtemplate/template.go b/backend/app/services/emailtemplate/template.gonew file mode 100644index 00000000..f34be6a8--- /dev/null+++ b/backend/app/services/emailtemplate/template.go@@ -0,0 +1,74 @@+// Package emailtemplate renders every outgoing Traceway email through one+// embedded HTML layout so they all share the same look: centered logo,+// headline, white content card with optional badge/details/code block, a+// single action button, a plain-link fallback and a footer.+package emailtemplate++import (+ "bytes"+ _ "embed"+ "html/template"+ "strings"+)++//go:embed base.gohtml+var baseTemplateSource string++var baseTemplate = template.Must(template.New("base").Funcs(template.FuncMap{+ "nl2br": func(s string) template.HTML {+ return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(s), "\n", "<br>"))+ },+}).Parse(baseTemplateSource))++const (+ ColorCritical = "#cf222e"+ ColorWarning = "#9a6700"+ ColorInfo = "#0969da"+)++type Detail struct {+ Label string+ Value string+}++type Button struct {+ Label string+ URL string+}++type Data struct {+ // Preheader is the hidden inbox preview text.+ Preheader string+ LogoURL string+ Title string+ // Badge is an optional severity chip above the content (e.g. "CRITICAL").+ Badge string+ BadgeColor string+ Paragraphs []string+ Details []Detail+ CodeBlock string+ // Button renders in the dashboard's outline style; severity only ever+ // colors the badge.+ Button *Button+ FooterNote string+}++func Render(d Data) (string, error) {+ if d.BadgeColor == "" {+ d.BadgeColor = ColorInfo+ }+ if d.Preheader == "" && len(d.Paragraphs) > 0 {+ d.Preheader = d.Paragraphs[0]+ }++ var buf bytes.Buffer+ if err := baseTemplate.Execute(&buf, d); err != nil {+ return "", err+ }+ return buf.String(), nil+}++// LogoURL builds the logo image reference served by the dashboard.+func LogoURL(baseURL string) string {+ return strings.TrimRight(baseURL, "/") + "/traceway-mark.png"+}diff --git a/backend/app/services/emailtemplate/template_test.go b/backend/app/services/emailtemplate/template_test.gonew file mode 100644index 00000000..9cfc2497--- /dev/null+++ b/backend/app/services/emailtemplate/template_test.go@@ -0,0 +1,119 @@+package emailtemplate++import (+ "io"+ "mime"+ "mime/multipart"+ "mime/quotedprintable"+ "net/mail"+ "strings"+ "testing"+)++func TestRenderEscapesAndIncludesContent(t *testing.T) {+ html, err := Render(Data{+ LogoURL: "https://traceway.example.com/traceway-mark.png",+ Title: "[Project <X>] New error: *traceway.StackTraceError",+ Badge: "CRITICAL",+ BadgeColor: ColorCritical,+ Paragraphs: []string{"A new error has been detected.\nSecond line."},+ Details: []Detail{{Label: "Hash", Value: "9c7bc73da37328f2"}},+ CodeBlock: "err := <nil>\n\tat main.go:1",+ Button: &Button{Label: "View Issue", URL: "https://traceway.example.com/issues/abc"},+ FooterNote: "You are receiving this because a rule fired.",+ })+ if err != nil {+ t.Fatalf("Render failed: %v", err)+ }++ for _, want := range []string{+ "[Project <X>] New error: *traceway.StackTraceError",+ "CRITICAL",+ "A new error has been detected.<br>Second line.",+ "9c7bc73da37328f2",+ "err := <nil>",+ `href="https://traceway.example.com/issues/abc"`,+ "View Issue",+ "Button not working?",+ "You are receiving this because a rule fired.",+ } {+ if !strings.Contains(html, want) {+ t.Errorf("rendered HTML missing %q", want)+ }+ }+}++func TestRenderButtonIsOutlineStyle(t *testing.T) {+ html, err := Render(Data{Title: "t", Button: &Button{Label: "Go", URL: "https://x"}})+ if err != nil {+ t.Fatalf("Render failed: %v", err)+ }+ if !strings.Contains(html, "border:1px solid #d1d9e0;border-radius:6px;background-color:#ffffff;") {+ t.Error("expected the outline button style")+ }+}++func TestBuildMIMEMultipart(t *testing.T) {+ raw, err := BuildMIME("[email protected]", []string{"[email protected]"},+ "[CRITICAL] New error: über long subject", "plain text body", "<html><body>hi</body></html>")+ if err != nil {+ t.Fatalf("BuildMIME failed: %v", err)+ }++ msg, err := mail.ReadMessage(strings.NewReader(string(raw)))+ if err != nil {+ t.Fatalf("message does not parse: %v", err)+ }++ dec := new(mime.WordDecoder)+ subject, err := dec.DecodeHeader(msg.Header.Get("Subject"))+ if err != nil {+ t.Fatalf("subject does not decode: %v", err)+ }+ if subject != "[CRITICAL] New error: über long subject" {+ t.Errorf("unexpected subject: %q", subject)+ }++ mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))+ if err != nil || mediaType != "multipart/alternative" {+ t.Fatalf("unexpected content type %q (err %v)", mediaType, err)+ }++ mr := multipart.NewReader(msg.Body, params["boundary"])+ var bodies []string+ for {+ part, err := mr.NextPart()+ if err == io.EOF {+ break+ }+ if err != nil {+ t.Fatalf("reading part: %v", err)+ }+ body, err := io.ReadAll(quotedprintable.NewReader(part))+ if err != nil {+ t.Fatalf("decoding part: %v", err)+ }+ bodies = append(bodies, string(body))+ }+ if len(bodies) != 2 || bodies[0] != "plain text body" || bodies[1] != "<html><body>hi</body></html>" {+ t.Errorf("unexpected part bodies: %#v", bodies)+ }+}++func TestBuildMIMEPlainOnly(t *testing.T) {+ raw, err := BuildMIME("[email protected]", []string{"[email protected]"}, "subject", "just text", "")+ if err != nil {+ t.Fatalf("BuildMIME failed: %v", err)+ }+ msg, err := mail.ReadMessage(strings.NewReader(string(raw)))+ if err != nil {+ t.Fatalf("message does not parse: %v", err)+ }+ body, err := io.ReadAll(quotedprintable.NewReader(msg.Body))+ if err != nil {+ t.Fatalf("decoding body: %v", err)+ }+ if string(body) != "just text" {+ t.Errorf("unexpected body: %q", body)+ }+}