diff --git a/adapters/mail/amazon_ses/send.go b/adapters/mail/amazon_ses/send.go index 602f1b4..b7fed88 100644 --- a/adapters/mail/amazon_ses/send.go +++ b/adapters/mail/amazon_ses/send.go @@ -10,10 +10,34 @@ 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{} + 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{ @@ -21,20 +45,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 +86,42 @@ 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"), + } + } + + 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), + 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, }, } - client, err := adapter.NewClient(ctx) - if err != nil { - return mail.Err("create SES client", err) + if len(headers) > 0 { + message.Content.Simple.Headers = headers } - 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/fake/adapter.go b/adapters/mail/fake/adapter.go index a6e2985..f66851c 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. @@ -28,6 +29,10 @@ type SendCall struct { HTML string Attachments int Input entities.MailInput + Text string + Headers []mailables.Header + // ConfigurationSet is the SES configuration set it went out with. + ConfigurationSet string } // 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..dbd5c32 100644 --- a/adapters/mail/smtp/send.go +++ b/adapters/mail/smtp/send.go @@ -43,6 +43,10 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro message.SetHeader("Bcc", input.Envelope.Bcc.String()...) } + if err := setExtraHeaders(message, input); err != nil { + return mail.Err("validate", err) + } + if len(input.Attachments) > 0 { for _, attachment := range input.Attachments { message.Attach(attachment.Name, @@ -58,7 +62,7 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro } } - 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 { @@ -67,3 +71,35 @@ func (adapter *Adapter) Send(ctx context.Context, input entities.MailInput) erro return nil } + +// 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) + } + + 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 +// 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/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..23a3f0f 100644 --- a/entities/mailables/content.go +++ b/entities/mailables/content.go @@ -11,10 +11,26 @@ 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 } 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..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 @@ -7,10 +9,41 @@ 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 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. + // 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 } +// 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 + Value string +} + func (envelope *Envelope) Merge(override Envelope) Envelope { if override.From != nil { envelope.From = override.From @@ -36,5 +69,13 @@ func (envelope *Envelope) Merge(override Envelope) Envelope { envelope.Subject = override.Subject } + for _, header := range override.Headers { + envelope.Headers = setHeader(envelope.Headers, header) + } + + if override.ConfigurationSet != "" { + envelope.ConfigurationSet = override.ConfigurationSet + } + return *envelope } 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/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/adapters/mail/amazon_ses/send_test.go b/tests/adapters/mail/amazon_ses/send_test.go new file mode 100644 index 0000000..27a7161 --- /dev/null +++ b/tests/adapters/mail/amazon_ses/send_test.go @@ -0,0 +1,112 @@ +package amazon_ses_test + +import ( + "bytes" + "context" + "encoding/json" + "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) { + 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") + _, _ = 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"} + input := entities.MailInput{Envelope: envelope, Html: html, Text: plain} + + if err := adapter.Send(context.Background(), input); 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: "Hello
" { + t.Fatalf("Html = %#v, wantHello
", 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) + } +} diff --git a/tests/adapters/mail/smtp/send_test.go b/tests/adapters/mail/smtp/send_test.go new file mode 100644 index 0000000..8973e84 --- /dev/null +++ b/tests/adapters/mail/smtp/send_test.go @@ -0,0 +1,195 @@ +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: "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: "