From b6290e991bab134710a558b7702d742af286efdd Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Tue, 24 Nov 2026 14:54:24 +0000 Subject: [PATCH 1/6] feat(mail): send headers, a plain text part and an ses configuration set Bulk mail needs a List-Unsubscribe header and a text part, and marketing mail needs its own SES configuration set so its bounces and complaints are reported apart from transactional mail. Envelope gains Headers and ConfigurationSet, merged over the default envelope; Content gains an optional TextView. SES sends all three; SMTP sends the headers, the configuration set as X-SES-CONFIGURATION-SET, and the text with the HTML as its alternative. --- adapters/mail/amazon_ses/send.go | 71 ++++++++++++++++++------- adapters/mail/amazon_ses/send_test.go | 71 +++++++++++++++++++++++++ adapters/mail/fake/adapter.go | 17 +++--- adapters/mail/fake/send.go | 15 +++--- adapters/mail/smtp/send.go | 17 +++++- entities/mail.go | 2 + entities/mailables/content.go | 20 ++++++- entities/mailables/envelope.go | 23 ++++++++ mail/send.go | 11 +++- tests/mail/mail/welcome.txt | 1 + tests/mail/send_test.go | 76 ++++++++++++++++++++++++++- 11 files changed, 287 insertions(+), 37 deletions(-) create mode 100644 adapters/mail/amazon_ses/send_test.go create mode 100644 tests/mail/mail/welcome.txt diff --git a/adapters/mail/amazon_ses/send.go b/adapters/mail/amazon_ses/send.go index 602f1b4..f4dfcaa 100644 --- a/adapters/mail/amazon_ses/send.go +++ b/adapters/mail/amazon_ses/send.go @@ -10,8 +10,28 @@ import ( "github.com/gonstruct/providers/mail" ) -//nolint:cyclop,funlen func (adapter Adapter) Send(ctx context.Context, input entities.MailInput) error { + message, err := buildMessage(input) + if err != nil { + return err + } + + client, err := adapter.NewClient(ctx) + if err != nil { + return mail.Err("create SES client", err) + } + + if _, err := client.SendEmail(ctx, message); err != nil { + return mail.Err("send via SES", err) + } + + return nil +} + +// buildMessage is the input as SES takes it. +// +//nolint:cyclop,funlen +func buildMessage(input entities.MailInput) (*sesv2.SendEmailInput, error) { message := &sesv2.SendEmailInput{} var subject *types.Content @@ -21,20 +41,20 @@ func (adapter Adapter) Send(ctx context.Context, input entities.MailInput) error Charset: aws.String("UTF-8"), } } else { - return mail.Err("validate", mail.ErrNoSubject) + return nil, mail.Err("validate", mail.ErrNoSubject) } if input.Envelope.From != nil { message.FromEmailAddress = aws.String(input.Envelope.From.String()) } else { - return mail.Err("validate", mail.ErrNoSender) + return nil, mail.Err("validate", mail.ErrNoSender) } message.Destination = &types.Destination{} if len(input.Envelope.To) > 0 { message.Destination.ToAddresses = input.Envelope.To.String() } else { - return mail.Err("validate", mail.ErrNoRecipients) + return nil, mail.Err("validate", mail.ErrNoRecipients) } if input.Envelope.ReplyTo != nil { @@ -62,28 +82,39 @@ func (adapter Adapter) Send(ctx context.Context, input entities.MailInput) error } } + body := &types.Body{ + Html: &types.Content{ + Data: aws.String(input.Html.String()), + Charset: aws.String("UTF-8"), + }, + } + if input.Text.Len() > 0 { + body.Text = &types.Content{ + Data: aws.String(input.Text.String()), + Charset: aws.String("UTF-8"), + } + } + + var headers []types.MessageHeader + for _, header := range input.Envelope.Headers { + headers = append(headers, types.MessageHeader{ + Name: aws.String(header.Name), + Value: aws.String(header.Value), + }) + } + message.Content = &types.EmailContent{ Simple: &types.Message{ - Subject: subject, - Body: &types.Body{ - Html: &types.Content{ - Data: aws.String(input.Html.String()), - Charset: aws.String("UTF-8"), - }, - // Text: // TODOd: Add text/plain support if needed, - }, + Subject: subject, + Body: body, Attachments: attachments, + Headers: headers, }, } - client, err := adapter.NewClient(ctx) - if err != nil { - return mail.Err("create SES client", err) - } - - if _, err := client.SendEmail(ctx, message); err != nil { - return mail.Err("send via SES", err) + if input.Envelope.ConfigurationSet != "" { + message.ConfigurationSetName = aws.String(input.Envelope.ConfigurationSet) } - return nil + return message, nil } diff --git a/adapters/mail/amazon_ses/send_test.go b/adapters/mail/amazon_ses/send_test.go new file mode 100644 index 0000000..b465d1a --- /dev/null +++ b/adapters/mail/amazon_ses/send_test.go @@ -0,0 +1,71 @@ +package amazon_ses + +import ( + "bytes" + "net/mail" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/gonstruct/providers/entities" + "github.com/gonstruct/providers/entities/mailables" +) + +func input(text string, envelope mailables.Envelope) entities.MailInput { + envelope.From = mailables.Address("news@example.com", "Example") + envelope.To = []*mail.Address{{Address: "user@example.com"}} + envelope.Subject = "What shipped" + + var html, plain bytes.Buffer + html.WriteString("

Hello

") + plain.WriteString(text) + + return entities.MailInput{Envelope: envelope, Html: html, Text: plain} +} + +func TestBuildMessage_CarriesHeadersTextAndConfigurationSet(t *testing.T) { + message, err := buildMessage(input("Hello", mailables.Envelope{ + Headers: []mailables.Header{ + {Name: "List-Unsubscribe", Value: ""}, + {Name: "List-Unsubscribe-Post", Value: "List-Unsubscribe=One-Click"}, + }, + ConfigurationSet: "marketing", + })) + if err != nil { + t.Fatalf("buildMessage() error = %v", err) + } + + simple := message.Content.Simple + if got := aws.ToString(simple.Body.Text.Data); got != "Hello" { + t.Fatalf("Text = %q, want Hello", got) + } + + if got := aws.ToString(simple.Body.Html.Data); got != "

Hello

" { + t.Fatalf("Html = %q, want

Hello

", got) + } + + if len(simple.Headers) != 2 || + aws.ToString(simple.Headers[0].Name) != "List-Unsubscribe" || + aws.ToString(simple.Headers[1].Value) != "List-Unsubscribe=One-Click" { + t.Fatalf("Headers = %#v, want both List-Unsubscribe headers in order", simple.Headers) + } + + if got := aws.ToString(message.ConfigurationSetName); got != "marketing" { + t.Fatalf("ConfigurationSetName = %q, want marketing", got) + } +} + +func TestBuildMessage_LeavesOutWhatTheMailHasNot(t *testing.T) { + message, err := buildMessage(input("", mailables.Envelope{})) + if err != nil { + t.Fatalf("buildMessage() error = %v", err) + } + + if message.Content.Simple.Body.Text != nil { + t.Fatalf("Text = %#v, want none", message.Content.Simple.Body.Text) + } + + if message.Content.Simple.Headers != nil || message.ConfigurationSetName != nil { + t.Fatalf("want no headers and no configuration set, got %#v and %v", + message.Content.Simple.Headers, message.ConfigurationSetName) + } +} diff --git a/adapters/mail/fake/adapter.go b/adapters/mail/fake/adapter.go index a6e2985..5cb5ce2 100644 --- a/adapters/mail/fake/adapter.go +++ b/adapters/mail/fake/adapter.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/gonstruct/providers/entities" + "github.com/gonstruct/providers/entities/mailables" ) // Adapter is a fake mail adapter for testing. @@ -22,12 +23,16 @@ type Adapter struct { } type SendCall struct { - To []string - From string - Subject string - HTML string - Attachments int - Input entities.MailInput + To []string + From string + Subject string + HTML string + Text string + Headers []mailables.Header + // ConfigurationSet is the SES configuration set it went out with. + ConfigurationSet string + Attachments int + Input entities.MailInput } // New creates a new fake mail adapter. diff --git a/adapters/mail/fake/send.go b/adapters/mail/fake/send.go index b0a8a38..20e1ebe 100644 --- a/adapters/mail/fake/send.go +++ b/adapters/mail/fake/send.go @@ -28,12 +28,15 @@ func (a *Adapter) Send(ctx context.Context, input entities.MailInput) error { } call := SendCall{ - To: to, - From: from, - Subject: envelope.Subject, - HTML: input.Html.String(), - Attachments: len(input.Attachments), - Input: input, + To: to, + From: from, + Subject: envelope.Subject, + HTML: input.Html.String(), + Text: input.Text.String(), + Headers: envelope.Headers, + ConfigurationSet: envelope.ConfigurationSet, + Attachments: len(input.Attachments), + Input: input, } a.mu.Lock() diff --git a/adapters/mail/smtp/send.go b/adapters/mail/smtp/send.go index e90a705..bb9faf7 100644 --- a/adapters/mail/smtp/send.go +++ b/adapters/mail/smtp/send.go @@ -43,6 +43,14 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro message.SetHeader("Bcc", input.Envelope.Bcc.String()...) } + for _, header := range input.Envelope.Headers { + message.SetHeader(header.Name, header.Value) + } + + if input.Envelope.ConfigurationSet != "" { + message.SetHeader("X-SES-CONFIGURATION-SET", input.Envelope.ConfigurationSet) + } + if len(input.Attachments) > 0 { for _, attachment := range input.Attachments { message.Attach(attachment.Name, @@ -58,7 +66,14 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro } } - message.SetBody("text/html", input.Html.String()) + // With a text version the HTML is its alternative, last, as the one a + // client prefers when it can show it. + if input.Text.Len() > 0 { + message.SetBody("text/plain", input.Text.String()) + message.AddAlternative("text/html", input.Html.String()) + } else { + message.SetBody("text/html", input.Html.String()) + } dialer := gomail.NewDialer(adapter.Host, adapter.Port, adapter.Username, adapter.Password) if err := dialer.DialAndSend(message); err != nil { diff --git a/entities/mail.go b/entities/mail.go index 785076e..c251ab8 100644 --- a/entities/mail.go +++ b/entities/mail.go @@ -10,4 +10,6 @@ type MailInput struct { Envelope mailables.Envelope Attachments mailables.AttachmentSlice Html bytes.Buffer + // Text is the plain text version, empty when the mail has none. + Text bytes.Buffer } diff --git a/entities/mailables/content.go b/entities/mailables/content.go index c4723ac..3ae3dff 100644 --- a/entities/mailables/content.go +++ b/entities/mailables/content.go @@ -10,11 +10,27 @@ import ( type Content struct { View string - With map[string]any + // TextView is the plain text version, rendered with the same With and + // sent beside the HTML. Without one the mail is HTML alone. + TextView string + With map[string]any } func (content Content) Parse(templates embed.FS) (bytes.Buffer, error) { - template, err := template.ParseFS(templates, path.Join("mail", content.View)) + return content.parse(templates, content.View) +} + +// ParseText renders the plain text version, nothing when there is none. +func (content Content) ParseText(templates embed.FS) (bytes.Buffer, error) { + if content.TextView == "" { + return bytes.Buffer{}, nil + } + + return content.parse(templates, content.TextView) +} + +func (content Content) parse(templates embed.FS, view string) (bytes.Buffer, error) { + template, err := template.ParseFS(templates, path.Join("mail", view)) if err != nil { return bytes.Buffer{}, fmt.Errorf("failed to parse email template: %w", err) } diff --git a/entities/mailables/envelope.go b/entities/mailables/envelope.go index 1826f49..9efc058 100644 --- a/entities/mailables/envelope.go +++ b/entities/mailables/envelope.go @@ -7,10 +7,25 @@ type Envelope struct { Bcc addressSlice ReplyTo *address Subject string + // Headers are added to the message as they are, in order: a + // List-Unsubscribe, an X-Entity-Ref-ID. The ones the envelope already + // sets (From, To, Subject and the like) are not for here. + Headers []Header + // ConfigurationSet is the Amazon SES configuration set the mail goes out + // with, which decides where its bounces and complaints are reported. + // Over SMTP it travels as X-SES-CONFIGURATION-SET, which SES's SMTP + // interface reads and any other server ignores. + ConfigurationSet string // Tags []string // Metadata map[string]any } +// Header is one header of a message. +type Header struct { + Name string + Value string +} + func (envelope *Envelope) Merge(override Envelope) Envelope { if override.From != nil { envelope.From = override.From @@ -36,5 +51,13 @@ func (envelope *Envelope) Merge(override Envelope) Envelope { envelope.Subject = override.Subject } + if len(override.Headers) > 0 { + envelope.Headers = append(envelope.Headers, override.Headers...) + } + + if override.ConfigurationSet != "" { + envelope.ConfigurationSet = override.ConfigurationSet + } + return *envelope } diff --git a/mail/send.go b/mail/send.go index 58b3fcb..d81682a 100644 --- a/mail/send.go +++ b/mail/send.go @@ -11,7 +11,14 @@ func Send(mailable contracts.Mailable, optionSlice ...Option) error { envelope := buildEnvelope(options.DefaultEnvelope, mailable.Envelope()) - content, err := mailable.Content().Parse(options.Templates) + view := mailable.Content() + + content, err := view.Parse(options.Templates) + if err != nil { + return err + } + + text, err := view.ParseText(options.Templates) if err != nil { return err } @@ -20,6 +27,7 @@ func Send(mailable contracts.Mailable, optionSlice ...Option) error { Envelope: envelope, Attachments: mailable.Attachments(), Html: content, + Text: text, }) } @@ -32,6 +40,7 @@ func buildEnvelope(defaultEnvelope *mailables.Envelope, override mailables.Envel base.To = append(base.To[:0:0], defaultEnvelope.To...) base.Cc = append(base.Cc[:0:0], defaultEnvelope.Cc...) base.Bcc = append(base.Bcc[:0:0], defaultEnvelope.Bcc...) + base.Headers = append(base.Headers[:0:0], defaultEnvelope.Headers...) return base.Merge(override) } diff --git a/tests/mail/mail/welcome.txt b/tests/mail/mail/welcome.txt new file mode 100644 index 0000000..3b96254 --- /dev/null +++ b/tests/mail/mail/welcome.txt @@ -0,0 +1 @@ +Hello {{ .name }} diff --git a/tests/mail/send_test.go b/tests/mail/send_test.go index 85d3034..b68f656 100644 --- a/tests/mail/send_test.go +++ b/tests/mail/send_test.go @@ -13,7 +13,7 @@ import ( pmail "github.com/gonstruct/providers/mail" ) -//go:embed mail/*.html +//go:embed mail/* var testTemplatesFS embed.FS type testMailable struct { @@ -301,3 +301,77 @@ func equalStrings(got, want []string) bool { } var _ contracts.Mail = (*capturingAdapter)(nil) + +func TestSend_RendersTextAndMergesHeadersAndConfigurationSet(t *testing.T) { + fake := pmail.Fake( + pmail.WithFakeTemplates(testTemplatesFS), + pmail.WithFakeDefaultEnvelope(mailables.Envelope{ + From: mailables.Address("noreply@example.com", "Example App"), + Headers: []mailables.Header{{Name: "X-App", Value: "example"}}, + ConfigurationSet: "transactional", + }), + ) + + send := func(name string, envelope mailables.Envelope) { + t.Helper() + + envelope.Subject = "Welcome" + envelope.To = []*mail.Address{{Address: "user@example.com"}} + + err := pmail.Send(testMailable{ + envelope: envelope, + content: mailables.Content{ + View: "welcome.html", + TextView: "welcome.txt", + With: map[string]any{"name": name}, + }, + }) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + } + + send("First", mailables.Envelope{ + Headers: []mailables.Header{{Name: "List-Unsubscribe", Value: ""}}, + ConfigurationSet: "marketing", + }) + send("Second", mailables.Envelope{}) + + first, second := fake.Calls[0], fake.Calls[1] + + if first.Text != "Hello First\n" { + t.Fatalf("Text = %q, want the rendered text view", first.Text) + } + + if len(first.Headers) != 2 || first.Headers[0].Name != "X-App" || first.Headers[1].Name != "List-Unsubscribe" { + t.Fatalf("Headers = %#v, want the default's then the mail's", first.Headers) + } + + if first.ConfigurationSet != "marketing" { + t.Fatalf("ConfigurationSet = %q, want the mail's own", first.ConfigurationSet) + } + + if len(second.Headers) != 1 || second.ConfigurationSet != "transactional" { + t.Fatalf("second mail got %#v and %q, want only the default's", second.Headers, second.ConfigurationSet) + } +} + +func TestSend_WithoutTextViewSendsHTMLAlone(t *testing.T) { + fake := pmail.Fake(pmail.WithFakeTemplates(testTemplatesFS)) + + err := pmail.Send(testMailable{ + envelope: mailables.Envelope{ + From: mailables.Address("noreply@example.com", ""), + Subject: "Welcome", + To: []*mail.Address{{Address: "user@example.com"}}, + }, + content: mailables.Content{View: "welcome.html", With: map[string]any{"name": "User"}}, + }) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + + if got := fake.Calls[0].Text; got != "" { + t.Fatalf("Text = %q, want none", got) + } +} From d91baf82d14f5474d8a9139ba4f699b1b016dcdc Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Tue, 24 Nov 2026 15:42:25 +0000 Subject: [PATCH 2/6] test(mail): move the ses test into tests/, through send Tests live in tests/, mirroring the code. The test now sends through Adapter.Send against a local server standing in for SES (AWS_ENDPOINT_URL_SESV2), so it reads what is actually sent. --- adapters/mail/amazon_ses/send_test.go | 71 ------------- tests/adapters/mail/amazon_ses/send_test.go | 111 ++++++++++++++++++++ 2 files changed, 111 insertions(+), 71 deletions(-) delete mode 100644 adapters/mail/amazon_ses/send_test.go create mode 100644 tests/adapters/mail/amazon_ses/send_test.go diff --git a/adapters/mail/amazon_ses/send_test.go b/adapters/mail/amazon_ses/send_test.go deleted file mode 100644 index b465d1a..0000000 --- a/adapters/mail/amazon_ses/send_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package amazon_ses - -import ( - "bytes" - "net/mail" - "testing" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/gonstruct/providers/entities" - "github.com/gonstruct/providers/entities/mailables" -) - -func input(text string, envelope mailables.Envelope) entities.MailInput { - envelope.From = mailables.Address("news@example.com", "Example") - envelope.To = []*mail.Address{{Address: "user@example.com"}} - envelope.Subject = "What shipped" - - var html, plain bytes.Buffer - html.WriteString("

Hello

") - plain.WriteString(text) - - return entities.MailInput{Envelope: envelope, Html: html, Text: plain} -} - -func TestBuildMessage_CarriesHeadersTextAndConfigurationSet(t *testing.T) { - message, err := buildMessage(input("Hello", mailables.Envelope{ - Headers: []mailables.Header{ - {Name: "List-Unsubscribe", Value: ""}, - {Name: "List-Unsubscribe-Post", Value: "List-Unsubscribe=One-Click"}, - }, - ConfigurationSet: "marketing", - })) - if err != nil { - t.Fatalf("buildMessage() error = %v", err) - } - - simple := message.Content.Simple - if got := aws.ToString(simple.Body.Text.Data); got != "Hello" { - t.Fatalf("Text = %q, want Hello", got) - } - - if got := aws.ToString(simple.Body.Html.Data); got != "

Hello

" { - t.Fatalf("Html = %q, want

Hello

", got) - } - - if len(simple.Headers) != 2 || - aws.ToString(simple.Headers[0].Name) != "List-Unsubscribe" || - aws.ToString(simple.Headers[1].Value) != "List-Unsubscribe=One-Click" { - t.Fatalf("Headers = %#v, want both List-Unsubscribe headers in order", simple.Headers) - } - - if got := aws.ToString(message.ConfigurationSetName); got != "marketing" { - t.Fatalf("ConfigurationSetName = %q, want marketing", got) - } -} - -func TestBuildMessage_LeavesOutWhatTheMailHasNot(t *testing.T) { - message, err := buildMessage(input("", mailables.Envelope{})) - if err != nil { - t.Fatalf("buildMessage() error = %v", err) - } - - if message.Content.Simple.Body.Text != nil { - t.Fatalf("Text = %#v, want none", message.Content.Simple.Body.Text) - } - - if message.Content.Simple.Headers != nil || message.ConfigurationSetName != nil { - t.Fatalf("want no headers and no configuration set, got %#v and %v", - message.Content.Simple.Headers, message.ConfigurationSetName) - } -} diff --git a/tests/adapters/mail/amazon_ses/send_test.go b/tests/adapters/mail/amazon_ses/send_test.go new file mode 100644 index 0000000..0c409d1 --- /dev/null +++ b/tests/adapters/mail/amazon_ses/send_test.go @@ -0,0 +1,111 @@ +package amazon_ses_test + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/mail" + "testing" + + "github.com/gonstruct/providers/adapters/mail/amazon_ses" + "github.com/gonstruct/providers/entities" + "github.com/gonstruct/providers/entities/mailables" +) + +// sent is the part of SES v2's SendEmail request these tests read. +type sent struct { + ConfigurationSetName *string + Content struct { + Simple struct { + Body struct { + Html *struct{ Data string } + Text *struct{ Data string } + } + Headers []struct{ Name, Value string } + } + } +} + +// fakeSES points the SES client at a server that keeps the request it gets. +func fakeSES(t *testing.T) *sent { + t.Helper() + + request := &sent{} + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, incoming *http.Request) { + body, _ := io.ReadAll(incoming.Body) + if err := json.Unmarshal(body, request); err != nil { + t.Errorf("SES got a body that is not JSON: %s", body) + } + writer.Header().Set("Content-Type", "application/json") + _, _ = writer.Write([]byte(`{"MessageId":"test"}`)) + })) + t.Cleanup(server.Close) + t.Setenv("AWS_ENDPOINT_URL_SESV2", server.URL) + + return request +} + +func send(t *testing.T, text string, envelope mailables.Envelope) { + t.Helper() + + envelope.From = mailables.Address("news@example.com", "Example") + envelope.To = []*mail.Address{{Address: "user@example.com"}} + envelope.Subject = "What shipped" + + var html, plain bytes.Buffer + html.WriteString("

Hello

") + plain.WriteString(text) + + adapter := amazon_ses.Adapter{Region: "eu-west-1", Username: "key", Password: "secret"} + if err := adapter.Send(context.Background(), entities.MailInput{Envelope: envelope, Html: html, Text: plain}); err != nil { + t.Fatalf("Send() error = %v", err) + } +} + +func TestSend_CarriesHeadersTextAndConfigurationSet(t *testing.T) { + request := fakeSES(t) + + send(t, "Hello", mailables.Envelope{ + Headers: []mailables.Header{ + {Name: "List-Unsubscribe", Value: ""}, + {Name: "List-Unsubscribe-Post", Value: "List-Unsubscribe=One-Click"}, + }, + ConfigurationSet: "marketing", + }) + + simple := request.Content.Simple + if simple.Body.Text == nil || simple.Body.Text.Data != "Hello" { + t.Fatalf("Text = %#v, want Hello", simple.Body.Text) + } + + if simple.Body.Html == nil || simple.Body.Html.Data != "

Hello

" { + t.Fatalf("Html = %#v, want

Hello

", simple.Body.Html) + } + + if len(simple.Headers) != 2 || simple.Headers[0].Name != "List-Unsubscribe" || + simple.Headers[1].Value != "List-Unsubscribe=One-Click" { + t.Fatalf("Headers = %#v, want both List-Unsubscribe headers in order", simple.Headers) + } + + if request.ConfigurationSetName == nil || *request.ConfigurationSetName != "marketing" { + t.Fatalf("ConfigurationSetName = %v, want marketing", request.ConfigurationSetName) + } +} + +func TestSend_LeavesOutWhatTheMailHasNot(t *testing.T) { + request := fakeSES(t) + + send(t, "", mailables.Envelope{}) + + if request.Content.Simple.Body.Text != nil { + t.Fatalf("Text = %#v, want none", request.Content.Simple.Body.Text) + } + + if request.Content.Simple.Headers != nil || request.ConfigurationSetName != nil { + t.Fatalf("want no headers and no configuration set, got %#v and %v", + request.Content.Simple.Headers, request.ConfigurationSetName) + } +} From 7f3b28f57a75f0d8816976fed06df9a300902193 Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Tue, 24 Nov 2026 15:43:57 +0000 Subject: [PATCH 3/6] style(mail): satisfy lint in the ses and smtp adapters Split the SMTP adapter's headers and body out of Send, preallocate the SES headers but send none when there are none, and wrap a long line in the SES test. --- adapters/mail/amazon_ses/send.go | 7 +++- adapters/mail/smtp/send.go | 42 +++++++++++++-------- tests/adapters/mail/amazon_ses/send_test.go | 5 ++- 3 files changed, 36 insertions(+), 18 deletions(-) diff --git a/adapters/mail/amazon_ses/send.go b/adapters/mail/amazon_ses/send.go index f4dfcaa..43b3246 100644 --- a/adapters/mail/amazon_ses/send.go +++ b/adapters/mail/amazon_ses/send.go @@ -95,7 +95,7 @@ func buildMessage(input entities.MailInput) (*sesv2.SendEmailInput, error) { } } - var headers []types.MessageHeader + headers := make([]types.MessageHeader, 0, len(input.Envelope.Headers)) for _, header := range input.Envelope.Headers { headers = append(headers, types.MessageHeader{ Name: aws.String(header.Name), @@ -108,10 +108,13 @@ func buildMessage(input entities.MailInput) (*sesv2.SendEmailInput, error) { Subject: subject, Body: body, Attachments: attachments, - Headers: headers, }, } + if len(headers) > 0 { + message.Content.Simple.Headers = headers + } + if input.Envelope.ConfigurationSet != "" { message.ConfigurationSetName = aws.String(input.Envelope.ConfigurationSet) } diff --git a/adapters/mail/smtp/send.go b/adapters/mail/smtp/send.go index bb9faf7..d3f20a4 100644 --- a/adapters/mail/smtp/send.go +++ b/adapters/mail/smtp/send.go @@ -43,13 +43,7 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro message.SetHeader("Bcc", input.Envelope.Bcc.String()...) } - for _, header := range input.Envelope.Headers { - message.SetHeader(header.Name, header.Value) - } - - if input.Envelope.ConfigurationSet != "" { - message.SetHeader("X-SES-CONFIGURATION-SET", input.Envelope.ConfigurationSet) - } + setExtraHeaders(message, input) if len(input.Attachments) > 0 { for _, attachment := range input.Attachments { @@ -66,14 +60,7 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro } } - // With a text version the HTML is its alternative, last, as the one a - // client prefers when it can show it. - if input.Text.Len() > 0 { - message.SetBody("text/plain", input.Text.String()) - message.AddAlternative("text/html", input.Html.String()) - } else { - message.SetBody("text/html", input.Html.String()) - } + setBody(message, input) dialer := gomail.NewDialer(adapter.Host, adapter.Port, adapter.Username, adapter.Password) if err := dialer.DialAndSend(message); err != nil { @@ -82,3 +69,28 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro return nil } + +// setExtraHeaders sets the envelope's own headers, and its SES configuration +// set as the header SES's SMTP interface reads. +func setExtraHeaders(message *gomail.Message, input entities.MailInput) { + for _, header := range input.Envelope.Headers { + message.SetHeader(header.Name, header.Value) + } + + if input.Envelope.ConfigurationSet != "" { + message.SetHeader("X-SES-CONFIGURATION-SET", input.Envelope.ConfigurationSet) + } +} + +// setBody sets the HTML, and with a text version makes the HTML its +// alternative, last, as the one a client prefers when it can show it. +func setBody(message *gomail.Message, input entities.MailInput) { + if input.Text.Len() > 0 { + message.SetBody("text/plain", input.Text.String()) + message.AddAlternative("text/html", input.Html.String()) + + return + } + + message.SetBody("text/html", input.Html.String()) +} diff --git a/tests/adapters/mail/amazon_ses/send_test.go b/tests/adapters/mail/amazon_ses/send_test.go index 0c409d1..0725d47 100644 --- a/tests/adapters/mail/amazon_ses/send_test.go +++ b/tests/adapters/mail/amazon_ses/send_test.go @@ -36,9 +36,11 @@ func fakeSES(t *testing.T) *sent { request := &sent{} server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, incoming *http.Request) { body, _ := io.ReadAll(incoming.Body) + if err := json.Unmarshal(body, request); err != nil { t.Errorf("SES got a body that is not JSON: %s", body) } + writer.Header().Set("Content-Type", "application/json") _, _ = writer.Write([]byte(`{"MessageId":"test"}`)) })) @@ -60,7 +62,8 @@ func send(t *testing.T, text string, envelope mailables.Envelope) { plain.WriteString(text) adapter := amazon_ses.Adapter{Region: "eu-west-1", Username: "key", Password: "secret"} - if err := adapter.Send(context.Background(), entities.MailInput{Envelope: envelope, Html: html, Text: plain}); err != nil { + input := entities.MailInput{Envelope: envelope, Html: html, Text: plain} + if err := adapter.Send(context.Background(), input); err != nil { t.Fatalf("Send() error = %v", err) } } From d60bec75459a0c87a8aa1962208a964ad9864efc Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Tue, 24 Nov 2026 15:45:04 +0000 Subject: [PATCH 4/6] style(mail): fix whitespace lint in the ses test --- tests/adapters/mail/amazon_ses/send_test.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/tests/adapters/mail/amazon_ses/send_test.go b/tests/adapters/mail/amazon_ses/send_test.go index 0725d47..27a7161 100644 --- a/tests/adapters/mail/amazon_ses/send_test.go +++ b/tests/adapters/mail/amazon_ses/send_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "encoding/json" - "io" "net/http" "net/http/httptest" "net/mail" @@ -35,10 +34,8 @@ func fakeSES(t *testing.T) *sent { request := &sent{} server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, incoming *http.Request) { - body, _ := io.ReadAll(incoming.Body) - - if err := json.Unmarshal(body, request); err != nil { - t.Errorf("SES got a body that is not JSON: %s", body) + if err := json.NewDecoder(incoming.Body).Decode(request); err != nil { + t.Errorf("SES got a body that is not JSON: %v", err) } writer.Header().Set("Content-Type", "application/json") @@ -63,6 +60,7 @@ func send(t *testing.T, text string, envelope mailables.Envelope) { adapter := amazon_ses.Adapter{Region: "eu-west-1", Username: "key", Password: "secret"} input := entities.MailInput{Envelope: envelope, Html: html, Text: plain} + if err := adapter.Send(context.Background(), input); err != nil { t.Fatalf("Send() error = %v", err) } From 9632738feb756b938bdc2de5d642c8156062e69a Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Tue, 24 Nov 2026 15:54:06 +0000 Subject: [PATCH 5/6] fix(mail): replace headers by name and refuse ones that break a mail A mail's header now takes the place of a default one of the same name, whatever its case, instead of going out twice. CheckHeaders refuses reserved names (From, To, Bcc and the like, which over SMTP would change who gets the mail), names SES would not take, and values with a line break; both adapters check before sending. TextView moves after With so unkeyed Content literals keep compiling, and SendCall keeps its fields' order. The SMTP adapter gets tests against a local server, and the merge test now has a default with room to spare, so it fails if a merge leaks into the next mail. --- adapters/mail/amazon_ses/send.go | 4 + adapters/mail/fake/adapter.go | 16 +-- adapters/mail/smtp/send.go | 4 + entities/mailables/content.go | 2 +- entities/mailables/envelope.go | 24 +++- mail/errors.go | 1 + mail/headers.go | 45 ++++++ tests/adapters/mail/smtp/send_test.go | 192 ++++++++++++++++++++++++++ tests/mail/headers_test.go | 36 +++++ tests/mail/send_test.go | 45 +++++- 10 files changed, 350 insertions(+), 19 deletions(-) create mode 100644 mail/headers.go create mode 100644 tests/adapters/mail/smtp/send_test.go create mode 100644 tests/mail/headers_test.go diff --git a/adapters/mail/amazon_ses/send.go b/adapters/mail/amazon_ses/send.go index 43b3246..b7fed88 100644 --- a/adapters/mail/amazon_ses/send.go +++ b/adapters/mail/amazon_ses/send.go @@ -34,6 +34,10 @@ func (adapter Adapter) Send(ctx context.Context, input entities.MailInput) error func buildMessage(input entities.MailInput) (*sesv2.SendEmailInput, error) { message := &sesv2.SendEmailInput{} + if err := mail.CheckHeaders(input.Envelope.Headers); err != nil { + return nil, mail.Err("validate", err) + } + var subject *types.Content if input.Envelope.Subject != "" { subject = &types.Content{ diff --git a/adapters/mail/fake/adapter.go b/adapters/mail/fake/adapter.go index 5cb5ce2..f66851c 100644 --- a/adapters/mail/fake/adapter.go +++ b/adapters/mail/fake/adapter.go @@ -23,16 +23,16 @@ type Adapter struct { } type SendCall struct { - To []string - From string - Subject string - HTML string - Text string - Headers []mailables.Header + To []string + From string + Subject string + HTML string + Attachments int + Input entities.MailInput + Text string + Headers []mailables.Header // ConfigurationSet is the SES configuration set it went out with. ConfigurationSet string - Attachments int - Input entities.MailInput } // New creates a new fake mail adapter. diff --git a/adapters/mail/smtp/send.go b/adapters/mail/smtp/send.go index d3f20a4..f913999 100644 --- a/adapters/mail/smtp/send.go +++ b/adapters/mail/smtp/send.go @@ -13,6 +13,10 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro _ = ctx // gomail doesn't support context, but we accept it for interface compatibility message := gomail.NewMessage() + if err := mail.CheckHeaders(input.Envelope.Headers); err != nil { + return mail.Err("validate", err) + } + if input.Envelope.Subject != "" { message.SetHeader("Subject", input.Envelope.Subject) } else { diff --git a/entities/mailables/content.go b/entities/mailables/content.go index 3ae3dff..23a3f0f 100644 --- a/entities/mailables/content.go +++ b/entities/mailables/content.go @@ -10,10 +10,10 @@ import ( type Content struct { View string + With map[string]any // TextView is the plain text version, rendered with the same With and // sent beside the HTML. Without one the mail is HTML alone. TextView string - With map[string]any } func (content Content) Parse(templates embed.FS) (bytes.Buffer, error) { diff --git a/entities/mailables/envelope.go b/entities/mailables/envelope.go index 9efc058..400bdfe 100644 --- a/entities/mailables/envelope.go +++ b/entities/mailables/envelope.go @@ -1,5 +1,7 @@ package mailables +import "strings" + type Envelope struct { From *address To addressSlice @@ -9,7 +11,8 @@ type Envelope struct { Subject string // Headers are added to the message as they are, in order: a // List-Unsubscribe, an X-Entity-Ref-ID. The ones the envelope already - // sets (From, To, Subject and the like) are not for here. + // sets (From, To, Subject and the like) are refused when sending, as + // is a name or value that would break the message (mail.CheckHeaders). Headers []Header // ConfigurationSet is the Amazon SES configuration set the mail goes out // with, which decides where its bounces and complaints are reported. @@ -20,6 +23,21 @@ type Envelope struct { // Metadata map[string]any } +// setHeader replaces the header of the same name, whatever its case, or +// adds it: a mail's List-Unsubscribe takes the default's place rather than +// going out beside it. +func setHeader(headers []Header, header Header) []Header { + for index := range headers { + if strings.EqualFold(headers[index].Name, header.Name) { + headers[index] = header + + return headers + } + } + + return append(headers, header) +} + // Header is one header of a message. type Header struct { Name string @@ -51,8 +69,8 @@ func (envelope *Envelope) Merge(override Envelope) Envelope { envelope.Subject = override.Subject } - if len(override.Headers) > 0 { - envelope.Headers = append(envelope.Headers, override.Headers...) + for _, header := range override.Headers { + envelope.Headers = setHeader(envelope.Headers, header) } if override.ConfigurationSet != "" { diff --git a/mail/errors.go b/mail/errors.go index c0ce886..3cc03be 100644 --- a/mail/errors.go +++ b/mail/errors.go @@ -11,6 +11,7 @@ var ( ErrNoSender = errors.New("no sender specified") ErrNoRecipients = errors.New("no recipients specified") ErrSendFailed = errors.New("failed to send email") + ErrHeader = errors.New("a header that cannot be sent") ) // Err wraps an error with mail context. diff --git a/mail/headers.go b/mail/headers.go new file mode 100644 index 0000000..f44e893 --- /dev/null +++ b/mail/headers.go @@ -0,0 +1,45 @@ +package mail + +import ( + "fmt" + "strings" + + "github.com/gonstruct/providers/entities/mailables" +) + +// reserved are the headers the envelope or the message itself writes. One +// set as an extra header would replace who the mail goes to, or break it. +var reserved = map[string]bool{ + "from": true, "to": true, "cc": true, "bcc": true, "reply-to": true, "sender": true, + "subject": true, "date": true, "message-id": true, "return-path": true, + "mime-version": true, "content-type": true, "content-transfer-encoding": true, + "x-ses-configuration-set": true, +} + +// CheckHeaders refuses headers an adapter must not send: a reserved name, +// a name that is not 1 to 126 printable ASCII characters without a colon +// (as SES takes them), and a value with a line break, which would start a +// header of its own. +func CheckHeaders(headers []mailables.Header) error { + for _, header := range headers { + if reserved[strings.ToLower(header.Name)] { + return fmt.Errorf("%w: %s is set by the envelope", ErrHeader, header.Name) + } + + if len(header.Name) == 0 || len(header.Name) > 126 { + return fmt.Errorf("%w: a name of %d characters", ErrHeader, len(header.Name)) + } + + for _, character := range header.Name { + if character < 33 || character > 126 || character == ':' { + return fmt.Errorf("%w: %q is not a header name", ErrHeader, header.Name) + } + } + + if strings.ContainsAny(header.Value, "\r\n") { + return fmt.Errorf("%w: %s has a line break", ErrHeader, header.Name) + } + } + + return nil +} diff --git a/tests/adapters/mail/smtp/send_test.go b/tests/adapters/mail/smtp/send_test.go new file mode 100644 index 0000000..4ca6b2f --- /dev/null +++ b/tests/adapters/mail/smtp/send_test.go @@ -0,0 +1,192 @@ +package smtp_test + +import ( + "bufio" + "bytes" + "context" + "errors" + "net" + "net/mail" + "strconv" + "strings" + "testing" + + "github.com/gonstruct/providers/adapters/mail/smtp" + "github.com/gonstruct/providers/entities" + "github.com/gonstruct/providers/entities/mailables" + pmail "github.com/gonstruct/providers/mail" +) + +// fakeSMTP is a server that takes one message and keeps it, with the +// addresses it was sent to. +type fakeSMTP struct { + port int + recipients []string + message chan *mail.Message +} + +func serve(t *testing.T) *fakeSMTP { + t.Helper() + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + + server := &fakeSMTP{port: listener.Addr().(*net.TCPAddr).Port, message: make(chan *mail.Message, 1)} + + go func() { + connection, err := listener.Accept() + if err != nil { + return + } + defer connection.Close() + + server.converse(t, connection) + }() + + return server +} + +func (server *fakeSMTP) converse(t *testing.T, connection net.Conn) { + t.Helper() + + reader := bufio.NewReader(connection) + reply := func(line string) { _, _ = connection.Write([]byte(line + "\r\n")) } + + reply("220 fake") + + for { + line, err := reader.ReadString('\n') + if err != nil { + return + } + + command := strings.ToUpper(strings.TrimSpace(line)) + + switch { + case strings.HasPrefix(command, "EHLO"), strings.HasPrefix(command, "HELO"): + reply("250 fake") + case strings.HasPrefix(command, "RCPT TO:"): + server.recipients = append(server.recipients, strings.Trim(strings.TrimSpace(line)[8:], "<>")) + reply("250 ok") + case command == "DATA": + reply("354 go on") + + var data bytes.Buffer + + for { + dataLine, err := reader.ReadString('\n') + if err != nil || dataLine == ".\r\n" { + break + } + + data.WriteString(dataLine) + } + + message, err := mail.ReadMessage(&data) + if err != nil { + t.Errorf("not a message: %v", err) + } + + server.message <- message + + reply("250 kept") + case command == "QUIT": + reply("221 bye") + + return + default: + reply("250 ok") + } + } +} + +func send(t *testing.T, server *fakeSMTP, text string, envelope mailables.Envelope) error { + t.Helper() + + envelope.From = mailables.Address("news@example.com", "Example") + envelope.To = []*mail.Address{{Address: "user@example.com"}} + envelope.Subject = "What shipped" + + var html, plain bytes.Buffer + html.WriteString("

Hello

") + plain.WriteString(text) + + adapter := &smtp.Adapter{Host: "127.0.0.1", Port: server.port} + input := entities.MailInput{Envelope: envelope, Html: html, Text: plain} + + return adapter.Send(context.Background(), input) +} + +func TestSend_CarriesHeadersTextAndConfigurationSet(t *testing.T) { + server := serve(t) + + err := send(t, server, "Hello", mailables.Envelope{ + Headers: []mailables.Header{ + {Name: "List-Unsubscribe", Value: ""}, + {Name: "List-Unsubscribe-Post", Value: "List-Unsubscribe=One-Click"}, + }, + ConfigurationSet: "marketing", + }) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + + message := <-server.message + for name, want := range map[string]string{ + "List-Unsubscribe": "", + "List-Unsubscribe-Post": "List-Unsubscribe=One-Click", + "X-Ses-Configuration-Set": "marketing", + } { + if got := message.Header.Get(name); got != want { + t.Errorf("%s = %q, want %q", name, got, want) + } + } + + contentType := message.Header.Get("Content-Type") + if !strings.HasPrefix(contentType, "multipart/alternative") { + t.Fatalf("Content-Type = %q, want multipart/alternative", contentType) + } + + var body bytes.Buffer + _, _ = body.ReadFrom(message.Body) + + text, html := strings.Index(body.String(), "Hello"), strings.Index(body.String(), "

Hello

") + if text < 0 || html < 0 || text > html { + t.Fatalf("want the text part first and the HTML after it, got %s", strconv.Quote(body.String())) + } +} + +func TestSend_WithoutTextSendsHTMLAlone(t *testing.T) { + server := serve(t) + + if err := send(t, server, "", mailables.Envelope{}); err != nil { + t.Fatalf("Send() error = %v", err) + } + + message := <-server.message + if got := message.Header.Get("Content-Type"); !strings.HasPrefix(got, "text/html") { + t.Fatalf("Content-Type = %q, want text/html", got) + } + + if got := message.Header.Get("X-Ses-Configuration-Set"); got != "" { + t.Fatalf("X-SES-CONFIGURATION-SET = %q, want none", got) + } +} + +func TestSend_RefusesAHeaderThatWouldAddARecipient(t *testing.T) { + server := serve(t) + + err := send(t, server, "", mailables.Envelope{ + Headers: []mailables.Header{{Name: "Bcc", Value: "someone@example.com"}}, + }) + if !errors.Is(err, pmail.ErrHeader) { + t.Fatalf("Send() error = %v, want ErrHeader", err) + } + + if len(server.recipients) != 0 { + t.Fatalf("recipients = %v, want none", server.recipients) + } +} diff --git a/tests/mail/headers_test.go b/tests/mail/headers_test.go new file mode 100644 index 0000000..b8e06b0 --- /dev/null +++ b/tests/mail/headers_test.go @@ -0,0 +1,36 @@ +package mail_test + +import ( + "errors" + "strings" + "testing" + + "github.com/gonstruct/providers/entities/mailables" + pmail "github.com/gonstruct/providers/mail" +) + +func TestCheckHeaders(t *testing.T) { + allowed := []mailables.Header{ + {Name: "List-Unsubscribe", Value: ", "}, + {Name: "List-Unsubscribe-Post", Value: "List-Unsubscribe=One-Click"}, + } + if err := pmail.CheckHeaders(allowed); err != nil { + t.Fatalf("CheckHeaders() = %v, want the unsubscribe headers allowed", err) + } + + refused := map[string]mailables.Header{ + "a reserved name": {Name: "bcc", Value: "someone@example.com"}, + "the configuration set": {Name: "X-SES-Configuration-Set", Value: "other"}, + "an empty name": {Name: "", Value: "x"}, + "a name with a colon": {Name: "X-A:B", Value: "x"}, + "a name with a space": {Name: "X A", Value: "x"}, + "a name with a line feed": {Name: "X-A\r\nBcc", Value: "x"}, + "a name too long": {Name: strings.Repeat("X", 127), Value: "x"}, + "a value with a break": {Name: "X-A", Value: "x\r\nBcc: someone@example.com"}, + } + for name, header := range refused { + if err := pmail.CheckHeaders([]mailables.Header{header}); !errors.Is(err, pmail.ErrHeader) { + t.Errorf("%s: CheckHeaders() = %v, want ErrHeader", name, err) + } + } +} diff --git a/tests/mail/send_test.go b/tests/mail/send_test.go index b68f656..c07e5ab 100644 --- a/tests/mail/send_test.go +++ b/tests/mail/send_test.go @@ -306,8 +306,13 @@ func TestSend_RendersTextAndMergesHeadersAndConfigurationSet(t *testing.T) { fake := pmail.Fake( pmail.WithFakeTemplates(testTemplatesFS), pmail.WithFakeDefaultEnvelope(mailables.Envelope{ - From: mailables.Address("noreply@example.com", "Example App"), - Headers: []mailables.Header{{Name: "X-App", Value: "example"}}, + From: mailables.Address("noreply@example.com", "Example App"), + // Room to spare, so a merge that appended to it would leak into + // the next mail. + Headers: append(make([]mailables.Header, 0, 4), + mailables.Header{Name: "X-App", Value: "example"}, + mailables.Header{Name: "List-Unsubscribe", Value: ""}, + ), ConfigurationSet: "transactional", }), ) @@ -332,7 +337,10 @@ func TestSend_RendersTextAndMergesHeadersAndConfigurationSet(t *testing.T) { } send("First", mailables.Envelope{ - Headers: []mailables.Header{{Name: "List-Unsubscribe", Value: ""}}, + Headers: []mailables.Header{ + {Name: "list-unsubscribe", Value: ""}, + {Name: "X-Entity-Ref-ID", Value: "1"}, + }, ConfigurationSet: "marketing", }) send("Second", mailables.Envelope{}) @@ -343,16 +351,25 @@ func TestSend_RendersTextAndMergesHeadersAndConfigurationSet(t *testing.T) { t.Fatalf("Text = %q, want the rendered text view", first.Text) } - if len(first.Headers) != 2 || first.Headers[0].Name != "X-App" || first.Headers[1].Name != "List-Unsubscribe" { - t.Fatalf("Headers = %#v, want the default's then the mail's", first.Headers) + wantFirst := []mailables.Header{ + {Name: "X-App", Value: "example"}, + {Name: "list-unsubscribe", Value: ""}, + {Name: "X-Entity-Ref-ID", Value: "1"}, + } + if !equalHeaders(first.Headers, wantFirst) { + t.Fatalf("Headers = %#v, want the mail's List-Unsubscribe in the default's place, then its own", first.Headers) } if first.ConfigurationSet != "marketing" { t.Fatalf("ConfigurationSet = %q, want the mail's own", first.ConfigurationSet) } - if len(second.Headers) != 1 || second.ConfigurationSet != "transactional" { - t.Fatalf("second mail got %#v and %q, want only the default's", second.Headers, second.ConfigurationSet) + wantSecond := []mailables.Header{ + {Name: "X-App", Value: "example"}, + {Name: "List-Unsubscribe", Value: ""}, + } + if !equalHeaders(second.Headers, wantSecond) || second.ConfigurationSet != "transactional" { + t.Fatalf("second mail got %#v and %q, want the default's untouched", second.Headers, second.ConfigurationSet) } } @@ -375,3 +392,17 @@ func TestSend_WithoutTextViewSendsHTMLAlone(t *testing.T) { t.Fatalf("Text = %q, want none", got) } } + +func equalHeaders(got, want []mailables.Header) bool { + if len(got) != len(want) { + return false + } + + for index := range got { + if got[index] != want[index] { + return false + } + } + + return true +} From b203b11b45952aa41729f6820fbf8f63352efb33 Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Tue, 24 Nov 2026 15:56:40 +0000 Subject: [PATCH 6/6] style(mail): satisfy lint in the smtp adapter and mail tests --- adapters/mail/smtp/send.go | 21 ++++++++----- tests/adapters/mail/smtp/send_test.go | 3 ++ tests/mail/send_test.go | 43 ++++++++++++++------------- 3 files changed, 38 insertions(+), 29 deletions(-) diff --git a/adapters/mail/smtp/send.go b/adapters/mail/smtp/send.go index f913999..dbd5c32 100644 --- a/adapters/mail/smtp/send.go +++ b/adapters/mail/smtp/send.go @@ -13,10 +13,6 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro _ = ctx // gomail doesn't support context, but we accept it for interface compatibility message := gomail.NewMessage() - if err := mail.CheckHeaders(input.Envelope.Headers); err != nil { - return mail.Err("validate", err) - } - if input.Envelope.Subject != "" { message.SetHeader("Subject", input.Envelope.Subject) } else { @@ -47,7 +43,9 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro message.SetHeader("Bcc", input.Envelope.Bcc.String()...) } - setExtraHeaders(message, input) + if err := setExtraHeaders(message, input); err != nil { + return mail.Err("validate", err) + } if len(input.Attachments) > 0 { for _, attachment := range input.Attachments { @@ -74,9 +72,14 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro return nil } -// setExtraHeaders sets the envelope's own headers, and its SES configuration -// set as the header SES's SMTP interface reads. -func setExtraHeaders(message *gomail.Message, input entities.MailInput) { +// setExtraHeaders sets the envelope's own headers, once they pass +// mail.CheckHeaders, and its SES configuration set as the header SES's SMTP +// interface reads. +func setExtraHeaders(message *gomail.Message, input entities.MailInput) error { + if err := mail.CheckHeaders(input.Envelope.Headers); err != nil { + return err + } + for _, header := range input.Envelope.Headers { message.SetHeader(header.Name, header.Value) } @@ -84,6 +87,8 @@ func setExtraHeaders(message *gomail.Message, input entities.MailInput) { if input.Envelope.ConfigurationSet != "" { message.SetHeader("X-SES-CONFIGURATION-SET", input.Envelope.ConfigurationSet) } + + return nil } // setBody sets the HTML, and with a text version makes the HTML its diff --git a/tests/adapters/mail/smtp/send_test.go b/tests/adapters/mail/smtp/send_test.go index 4ca6b2f..8973e84 100644 --- a/tests/adapters/mail/smtp/send_test.go +++ b/tests/adapters/mail/smtp/send_test.go @@ -32,6 +32,7 @@ func serve(t *testing.T) *fakeSMTP { if err != nil { t.Fatal(err) } + t.Cleanup(func() { _ = listener.Close() }) server := &fakeSMTP{port: listener.Addr().(*net.TCPAddr).Port, message: make(chan *mail.Message, 1)} @@ -70,6 +71,7 @@ func (server *fakeSMTP) converse(t *testing.T, connection net.Conn) { reply("250 fake") case strings.HasPrefix(command, "RCPT TO:"): server.recipients = append(server.recipients, strings.Trim(strings.TrimSpace(line)[8:], "<>")) + reply("250 ok") case command == "DATA": reply("354 go on") @@ -151,6 +153,7 @@ func TestSend_CarriesHeadersTextAndConfigurationSet(t *testing.T) { } var body bytes.Buffer + _, _ = body.ReadFrom(message.Body) text, html := strings.Index(body.String(), "Hello"), strings.Index(body.String(), "

Hello

") diff --git a/tests/mail/send_test.go b/tests/mail/send_test.go index c07e5ab..1e1f49a 100644 --- a/tests/mail/send_test.go +++ b/tests/mail/send_test.go @@ -302,6 +302,26 @@ func equalStrings(got, want []string) bool { var _ contracts.Mail = (*capturingAdapter)(nil) +// sendWelcome sends the welcome mail, with its text view, to name. +func sendWelcome(t *testing.T, name string, envelope mailables.Envelope) { + t.Helper() + + envelope.Subject = "Welcome" + envelope.To = []*mail.Address{{Address: "user@example.com"}} + + err := pmail.Send(testMailable{ + envelope: envelope, + content: mailables.Content{ + View: "welcome.html", + TextView: "welcome.txt", + With: map[string]any{"name": name}, + }, + }) + if err != nil { + t.Fatalf("Send() error = %v", err) + } +} + func TestSend_RendersTextAndMergesHeadersAndConfigurationSet(t *testing.T) { fake := pmail.Fake( pmail.WithFakeTemplates(testTemplatesFS), @@ -317,33 +337,14 @@ func TestSend_RendersTextAndMergesHeadersAndConfigurationSet(t *testing.T) { }), ) - send := func(name string, envelope mailables.Envelope) { - t.Helper() - - envelope.Subject = "Welcome" - envelope.To = []*mail.Address{{Address: "user@example.com"}} - - err := pmail.Send(testMailable{ - envelope: envelope, - content: mailables.Content{ - View: "welcome.html", - TextView: "welcome.txt", - With: map[string]any{"name": name}, - }, - }) - if err != nil { - t.Fatalf("Send() error = %v", err) - } - } - - send("First", mailables.Envelope{ + sendWelcome(t, "First", mailables.Envelope{ Headers: []mailables.Header{ {Name: "list-unsubscribe", Value: ""}, {Name: "X-Entity-Ref-ID", Value: "1"}, }, ConfigurationSet: "marketing", }) - send("Second", mailables.Envelope{}) + sendWelcome(t, "Second", mailables.Envelope{}) first, second := fake.Calls[0], fake.Calls[1]