Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(templates): resolve stylesheets from <link> tags on HTML import
Jonas Kaninda1b3029e0a7ab
diff --git a/internal/handlers/html_parser.go b/internal/handlers/html_parser.goindex f0da256..e032bb4 100644--- a/internal/handlers/html_parser.go+++ b/internal/handlers/html_parser.go@@ -26,7 +26,7 @@ var styleBlockRegex = regexp.MustCompile(`(?is)<style[^>]*>(.*?)</style>`)// extractStyleAndBody extracts CSS from <style> blocks and returns the cleaned HTML body.// If the HTML contains a <body> tag, only the body content is returned.-// All <style> blocks are removed from the returned HTML.+// All <style> blocks and stylesheet <link> tags are removed from the returned HTML.func extractStyleAndBody(htmlContent string) (css string, body string) {// Extract all <style> block contentsvar cssBlocks []string@@ -41,8 +41,9 @@ func extractStyleAndBody(htmlContent string) (css string, body string) {}css = strings.Join(cssBlocks, "\n\n")- // Remove <style> blocks from HTML+ // Remove <style> blocks and stylesheet <link> tags from HTMLcleaned := styleBlockRegex.ReplaceAllString(htmlContent, "")+ cleaned = stripStyleSheetLinks(cleaned)// Extract <body> content if presentbody = extractBody(cleaned)@@ -50,6 +51,60 @@ func extractStyleAndBody(htmlContent string) (css string, body string) {return css, body}+var (+ linkTagRegex = regexp.MustCompile(`(?is)<link\b[^>]*>`)+ relAttrRegex = regexp.MustCompile(`(?is)\brel\s*=\s*["']?([^"'>\s]+)`)+ hrefAttrRegex = regexp.MustCompile(`(?is)\bhref\s*=\s*["']([^"']+)["']`)+)++// isStyleSheetLink reports whether a <link ...> tag references a stylesheet.+func isStyleSheetLink(tag string) bool {+ rel := relAttrRegex.FindStringSubmatch(tag)+ return len(rel) >= 2 && strings.Contains(strings.ToLower(rel[1]), "stylesheet")+}++// extractStyleSheetLinks returns the stylesheet names referenced by+// <link rel="stylesheet" href="..."> tags, derived from each href's basename+// without its .css extension (e.g. "css/styles.css?v=2" -> "styles").+func extractStyleSheetLinks(htmlContent string) []string {+ var names []string+ for _, tag := range linkTagRegex.FindAllString(htmlContent, -1) {+ if !isStyleSheetLink(tag) {+ continue+ }+ href := hrefAttrRegex.FindStringSubmatch(tag)+ if len(href) < 2 {+ continue+ }+ if name := styleSheetNameFromHref(href[1]); name != "" {+ names = append(names, name)+ }+ }+ return names+}++func stripStyleSheetLinks(htmlContent string) string {+ return linkTagRegex.ReplaceAllStringFunc(htmlContent, func(tag string) string {+ if isStyleSheetLink(tag) {+ return ""+ }+ return tag+ })+}++func styleSheetNameFromHref(href string) string {+ h := strings.TrimSpace(href)+ if i := strings.IndexAny(h, "?#"); i >= 0 {+ h = h[:i]+ }+ h = strings.TrimRight(h, "/")+ if i := strings.LastIndexAny(h, `/\`); i >= 0 {+ h = h[i+1:]+ }+ h = strings.TrimSuffix(h, ".css")+ return strings.TrimSpace(h)+}+var bodyRegex = regexp.MustCompile(`(?is)<body[^>]*>(.*)</body>`)// extractBody extracts the inner content of the <body> tag.diff --git a/internal/handlers/html_parser_test.go b/internal/handlers/html_parser_test.gonew file mode 100644index 0000000..86eb9e5--- /dev/null+++ b/internal/handlers/html_parser_test.go@@ -0,0 +1,79 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package handlers++import (+ "strings"+ "testing"+)++func TestStyleSheetNameFromHref(t *testing.T) {+ cases := map[string]string{+ "styles.css": "styles",+ "css/styles.css": "styles",+ "/assets/css/main.css": "main",+ "styles.css?v=2": "styles",+ "theme.css#section": "theme",+ "https://x.io/base.css": "base",+ `a\b\win.css`: "win",+ "": "",+ }+ for in, want := range cases {+ if got := styleSheetNameFromHref(in); got != want {+ t.Errorf("styleSheetNameFromHref(%q) = %q, want %q", in, got, want)+ }+ }+}++func TestExtractStyleSheetLinks(t *testing.T) {+ html := `<head>+ <link rel="stylesheet" href="css/styles.css?v=2">+ <link href="other.css" rel="STYLESHEET"/>+ <link rel="icon" href="favicon.ico">+ <link rel=preload href="ignored.css">+ </head>`++ got := extractStyleSheetLinks(html)+ want := []string{"styles", "other"}+ if len(got) != len(want) {+ t.Fatalf("extractStyleSheetLinks = %v, want %v", got, want)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Errorf("extractStyleSheetLinks[%d] = %q, want %q", i, got[i], want[i])+ }+ }+}++func TestExtractStyleAndBodyStripsLinks(t *testing.T) {+ html := `<html><head>+ <style>.a{color:red}</style>+ <link rel="stylesheet" href="styles.css">+ </head><body><p>Hi</p></body></html>`++ css, body := extractStyleAndBody(html)+ if css != ".a{color:red}" {+ t.Errorf("css = %q, want %q", css, ".a{color:red}")+ }+ if strings.Contains(body, "<link") || strings.Contains(body, "<style") {+ t.Errorf("body still contains stripped tags: %q", body)+ }+ if !strings.Contains(body, "<p>Hi</p>") {+ t.Errorf("body missing content: %q", body)+ }+}diff --git a/internal/handlers/template_handler.go b/internal/handlers/template_handler.goindex 326c000..dd5bc40 100644--- a/internal/handlers/template_handler.go+++ b/internal/handlers/template_handler.go@@ -472,8 +472,9 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {return c.AbortBadRequest("could not derive template name from filename")}- // Extract CSS and HTML body+ // Extract CSS and HTML body, plus any <link rel="stylesheet"> referencescss, body := extractStyleAndBody(htmlContent)+ linkNames := extractStyleSheetLinks(htmlContent)// Try to extract a subject from <title>subject := extractTitle(htmlContent)@@ -494,29 +495,19 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {Name: name,DefaultLanguage: defaultLang,Description: fmt.Sprintf("Imported from %s", filename),+ SampleData: "{}",}if err := h.repo.Create(tmpl); err != nil {return c.AbortConflict("template with this name already exists")}- // Create stylesheet from extracted CSS (if any)- var stylesheetID *uint- if css != "" {- ss := &models.StyleSheet{- UserID: scope.UserID,- WorkspaceID: scope.WorkspaceID,- Name: name + "-styles",- CSS: css,- }- if err := h.stylesheetRepo.Create(ss); err == nil {- stylesheetID = &ss.ID- }- }+ stylesheetID := h.resolveImportedStyleSheet(scope, name, css, linkNames)// Create version v1v := &models.TemplateVersion{TemplateID: tmpl.ID,Version: 1,+ SampleData: "{}",StyleSheetID: stylesheetID,}if err := h.versionRepo.Create(v); err != nil {@@ -542,3 +533,40 @@ func (h *TemplateHandler) ImportHTML(c *okapi.Context) error {return created(c, tmpl)}++// resolveImportedStyleSheet resolves the stylesheet for an HTML import+func (h *TemplateHandler) resolveImportedStyleSheet(scope repositories.ResourceScope, baseName, inlineCSS string, linkNames []string) *uint {+ for _, name := range linkNames {+ if name == "" {+ continue+ }+ if ss, err := h.stylesheetRepo.FindByNameInScope(scope, name); err == nil && ss != nil {+ return &ss.ID+ }+ }++ for _, name := range linkNames {+ if name != "" {+ return h.createStyleSheet(scope, name, inlineCSS)+ }+ }++ if strings.TrimSpace(inlineCSS) != "" {+ return findOrCreateStyleSheet(&ExportStyleSheet{Name: baseName + "-styles", CSS: inlineCSS}, scope, h.stylesheetRepo)+ }++ return nil+}++func (h *TemplateHandler) createStyleSheet(scope repositories.ResourceScope, name, css string) *uint {+ ss := &models.StyleSheet{+ UserID: scope.UserID,+ WorkspaceID: scope.WorkspaceID,+ Name: name,+ CSS: css,+ }+ if err := h.stylesheetRepo.Create(ss); err != nil {+ return nil+ }+ return &ss.ID+}