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
fix(email): break subject encoded-words only between words
Mike Kosuline7cbf438b1cf
diff --git a/internal/services/email/header_encoding_test.go b/internal/services/email/header_encoding_test.gonew file mode 100644index 0000000..3d85619--- /dev/null+++ b/internal/services/email/header_encoding_test.go@@ -0,0 +1,61 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package email++import (+ "mime"+ "net/mail"+ "regexp"+ "strings"+ "testing"+)++var encodedWordRe = regexp.MustCompile(`=\?[^?\s]+\?[QqBb]\?[^?\s]*\?=`)++// RFC 2047 ignores the whitespace between encoded-words, but some relays keep+// it, so a subject split mid-word arrives as "subscri ptions". Encoded-words+// must therefore break only at spaces; such a relay may still double one.+func TestBuildMessageSubjectSplitsBetweenWords(t *testing.T) {+ for _, subject := range []string{+ "Your availability alert — new rooms found for 3 subscriptions",+ "Réservation confirmée : votre séjour à l’hôtel Côte d’Azur commence bientôt",+ "Места появились по 3 подпискам",+ } {+ raw := buildMessage("[email protected]", []string{"[email protected]"},+ subject, "", "body", nil, nil, "", "", false)++ msg, err := mail.ReadMessage(strings.NewReader(string(raw)))+ if err != nil {+ t.Fatalf("built message does not parse: %v", err)+ }+ value := msg.Header.Get("Subject")+ if got, _ := new(mime.WordDecoder).DecodeHeader(value); got != subject {+ t.Errorf("subject %q decodes as %q", subject, got)+ }++ naive := encodedWordRe.ReplaceAllStringFunc(value, func(w string) string {+ s, _ := new(mime.WordDecoder).Decode(w)+ return s+ })+ if strings.Join(strings.Fields(naive), " ") != subject {+ t.Errorf("subject %q arrives as %q\nencoded: %s", subject, naive, value)+ }+ }+}diff --git a/internal/services/email/smtp_sender.go b/internal/services/email/smtp_sender.goindex 91251e3..116844f 100644--- a/internal/services/email/smtp_sender.go+++ b/internal/services/email/smtp_sender.go@@ -34,6 +34,7 @@ import ("slices""strings""time"+ "unicode/utf8""github.com/google/uuid""github.com/goposta/posta/internal/models"@@ -309,6 +310,38 @@ func isASCII(s string) bool {return true}+// encodeHeader encodes s as RFC 2047 encoded-words for an unstructured header+// such as Subject. RFC 2047 ignores the whitespace between encoded-words, but+// some relays keep it when they re-encode the header, so encoded-words break+// only at spaces; a break inside a word would reach the reader as a stray space.+func encodeHeader(s string) string {+ if mime.BEncoding.Encode("UTF-8", s) == s {+ return s+ }+ // 45 bytes encode to 60 base64 characters, which keeps each encoded-word+ // within the 75 characters RFC 2047 allows.+ const limit = 45+ chunks := []string{""}+ for i, w := range strings.Split(s, " ") {+ if i > 0 {+ w = " " + w+ }+ if n := len(chunks) - 1; chunks[n] != "" && len(chunks[n])+len(w) > limit {+ chunks = append(chunks, "")+ }+ for _, r := range w {+ if n := len(chunks) - 1; len(chunks[n])+utf8.RuneLen(r) > limit {+ chunks = append(chunks, "")+ }+ chunks[len(chunks)-1] += string(r)+ }+ }+ for i, c := range chunks {+ chunks[i] = "=?UTF-8?b?" + base64.StdEncoding.EncodeToString([]byte(c)) + "?="+ }+ return strings.Join(chunks, " ")+}+// hasHeader reports whether the caller-supplied headers already include key// (header names are case-insensitive per RFC 5322).func hasHeader(headers map[string]string, key string) bool {@@ -339,7 +372,7 @@ func buildMessage(from string, to []string, subject, htmlBody, textBody string,fmt.Fprintf(&b, "From: %s\r\n", from)fmt.Fprintf(&b, "To: %s\r\n", strings.Join(to, ", "))- fmt.Fprintf(&b, "Subject: %s\r\n", mime.QEncoding.Encode("UTF-8", subject))+ fmt.Fprintf(&b, "Subject: %s\r\n", encodeHeader(subject))// RFC 5322 requires Date and recommends Message-ID; relays are free to// forward a message without adding them, so emit both unless the caller