Skip to content

armgit / posta

Public Imported from GitHub
0

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.

feat(email): auto-suppress recipients on permanent (5xx) rejection (#86)

Jonas Kanindaee2cdc8efb30
diff --git a/.env.example b/.env.example
index 0f902f5..d9dd9f3 100644
--- a/.env.example
+++ b/.env.example
@@ -124,4 +124,8 @@ POSTA_INBOUND_SMTP_RATE_LIMIT=60
POSTA_INBOUND_SMTP_RATE_WINDOW=60
# Require new users to verify their email address before they can sign in.
# When true, signup sends a verification link and login is blocked until confirmed.
-POSTA_EMAIL_VERIFICATION_REQUIRED=false
\ No newline at end of file
+POSTA_EMAIL_VERIFICATION_REQUIRED=false
+# Adds a recipient to the suppression list when an
+# outbound send is permanently rejected (5xx at RCPT TO, e.g. 550 user
+# unknown), and stops retrying that message.
+POSTA_AUTO_SUPPRESS_ON_REJECT=true
\ No newline at end of file
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index 8e5166f..24b797e 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -317,6 +317,9 @@ func startEmbeddedWorker(db *gorm.DB,
}
handler.SetCampaignMessageRepo(repositories.NewCampaignMessageRepository(db))
handler.SetCampaignRepo(repositories.NewCampaignRepository(db))
+ handler.SetSuppressionRepo(repositories.NewSuppressionRepository(db))
+ handler.SetBounceRepo(repositories.NewBounceRepository(db))
+ handler.SetAutoSuppress(cfg.AutoSuppressOnReject)
handler.SetStamper(email.NewStamper("Posta", config.Version, []byte(cfg.JWTSecret)))
handler.OnSent(func() {
metrics.IncrementEmailSent()
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index 7aa8074..ff2c6aa 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -85,6 +85,9 @@ func runWorker() error {
}
handler.SetCampaignMessageRepo(repositories.NewCampaignMessageRepository(db))
handler.SetCampaignRepo(repositories.NewCampaignRepository(db))
+ handler.SetSuppressionRepo(repositories.NewSuppressionRepository(db))
+ handler.SetBounceRepo(repositories.NewBounceRepository(db))
+ handler.SetAutoSuppress(cfg.AutoSuppressOnReject)
handler.SetStamper(email.NewStamper("Posta", config.Version, []byte(cfg.JWTSecret)))
handler.OnSent(func() {
metrics.IncrementEmailSent()
diff --git a/examples/.env.example b/examples/.env.example
index 2483bf5..ff65757 100644
--- a/examples/.env.example
+++ b/examples/.env.example
@@ -95,4 +95,5 @@ [email protected]
POSTA_SYSTEM_SMTP_PASSWORD=secret
# Encryption mode: none, ssl, starttls
-POSTA_SYSTEM_SMTP_ENCRYPTION=starttls
\ No newline at end of file
+POSTA_SYSTEM_SMTP_ENCRYPTION=starttls
+POSTA_AUTO_SUPPRESS_ON_REJECT=true
\ No newline at end of file
diff --git a/internal/config/config.go b/internal/config/config.go
index 64bf68c..daee707 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -57,6 +57,11 @@ type Config struct {
WorkerConcurrency int
WorkerMaxRetries int
+ // AutoSuppressOnReject adds a recipient to the suppression list when an
+ // outbound send is permanently rejected (5xx at RCPT TO, e.g. 550 user
+ // unknown), and stops retrying that message.
+ AutoSuppressOnReject bool
+
// Webhook settings
WebhookMaxRetries int
WebhookTimeoutSecs int
@@ -175,9 +180,10 @@ func New() *Config {
CORSOrigins: goutils.Env("POSTA_CORS_ORIGINS", "*"),
- EmbeddedWorker: goutils.EnvBool("POSTA_EMBEDDED_WORKER", false),
- WorkerConcurrency: goutils.EnvInt("POSTA_WORKER_CONCURRENCY", 10),
- WorkerMaxRetries: goutils.EnvInt("POSTA_WORKER_MAX_RETRIES", 5),
+ EmbeddedWorker: goutils.EnvBool("POSTA_EMBEDDED_WORKER", false),
+ WorkerConcurrency: goutils.EnvInt("POSTA_WORKER_CONCURRENCY", 10),
+ WorkerMaxRetries: goutils.EnvInt("POSTA_WORKER_MAX_RETRIES", 5),
+ AutoSuppressOnReject: goutils.EnvBool("POSTA_AUTO_SUPPRESS_ON_REJECT", true),
WebhookMaxRetries: goutils.EnvInt("POSTA_WEBHOOK_MAX_RETRIES", 3),
WebhookTimeoutSecs: goutils.EnvInt("POSTA_WEBHOOK_TIMEOUT_SECS", 10),
@@ -290,7 +296,7 @@ func (c *Config) Initialize(app *okapi.Okapi) error {
})
app.WithOpenAPIDocs(okapi.OpenAPI{
Title: "Posta API",
- Version: "v1",
+ Version: "1",
License: okapi.License{
Name: "Apache-2.0",
URL: "http://www.apache.org/licenses/LICENSE-2.0",
@@ -298,7 +304,7 @@ func (c *Config) Initialize(app *okapi.Okapi) error {
Contact: okapi.Contact{
Name: "Posta",
URL: "https://github.com/goposta/posta",
- Email: "[email protected]",
+ Email: "[email protected]",
},
Servers: apiServers,
SecuritySchemes: c.securitySchemes,
diff --git a/internal/services/email/smtp_sender.go b/internal/services/email/smtp_sender.go
index 71c64d3..b97d2df 100644
--- a/internal/services/email/smtp_sender.go
+++ b/internal/services/email/smtp_sender.go
@@ -20,15 +20,45 @@ package email
import (
"crypto/tls"
"encoding/base64"
+ "errors"
"fmt"
"mime"
"net/mail"
"net/smtp"
+ "net/textproto"
"strings"
"github.com/goposta/posta/internal/models"
)
+// SendError carries structured information about an SMTP failure so callers can
+// distinguish a permanent recipient rejection (5xx at RCPT TO) from a transient
+// error worth retrying. Error() preserves the original human-readable string.
+type SendError struct {
+ Stage string // "RCPT TO", "MAIL FROM", "DATA", ...
+ Recipient string // bare recipient address, set for RCPT TO failures
+ Code int // SMTP reply code (e.g. 550); 0 when not an SMTP reply
+ Msg string // server reply text, incl. enhanced status code (5.1.1 ...)
+ Err error
+}
+
+// Permanent reports whether the failure is a permanent (5xx) SMTP rejection.
+func (e *SendError) Permanent() bool { return e.Code >= 500 && e.Code < 600 }
+
+func (e *SendError) Error() string { return e.Err.Error() }
+func (e *SendError) Unwrap() error { return e.Err }
+
+// smtpReply extracts the SMTP reply code and message from an error returned by
+// the net/smtp client. It returns (0, "") when err does not wrap a
+// *textproto.Error (e.g. a connection-level failure).
+func smtpReply(err error) (int, string) {
+ var t *textproto.Error
+ if errors.As(err, &t) {
+ return t.Code, t.Msg
+ }
+ return 0, ""
+}
+
type SMTPSender struct{}
func NewSMTPSender() *SMTPSender {
@@ -101,7 +131,7 @@ func (s *SMTPSender) Send(server *models.SMTPServer, from string, to []string, s
case models.EncryptionSTARTTLS:
return sendWithSTARTTLS(addr, auth, server.Host, envelopeFrom, to, msg)
default:
- return smtp.SendMail(addr, auth, envelopeFrom, to, msg)
+ return sendPlain(addr, auth, server.Host, envelopeFrom, to, msg)
}
}
@@ -148,6 +178,16 @@ func sendWithSTARTTLS(addr string, auth smtp.Auth, host string, from string, to
return sendViaClient(client, auth, from, to, msg)
}
+func sendPlain(addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {
+ client, err := smtp.Dial(addr)
+ if err != nil {
+ return fmt.Errorf("SMTP dial failed, host: %s, error: %w", host, err)
+ }
+ defer func() { _ = client.Close() }()
+
+ return sendViaClient(client, auth, from, to, msg)
+}
+
func sendViaClient(client *smtp.Client, auth smtp.Auth, from string, to []string, msg []byte) error {
if auth != nil {
if err := client.Auth(auth); err != nil {
@@ -156,28 +196,36 @@ func sendViaClient(client *smtp.Client, auth smtp.Auth, from string, to []string
}
if err := client.Mail(from); err != nil {
- return fmt.Errorf("SMTP MAIL FROM failed: %w", err)
+ return wrapSendError("MAIL FROM", from, fmt.Errorf("SMTP MAIL FROM failed: %w", err))
}
for _, addr := range to {
- if err := client.Rcpt(envelopeAddress(addr)); err != nil {
- return fmt.Errorf("SMTP RCPT TO failed: %w", err)
+ rcpt := envelopeAddress(addr)
+ if err := client.Rcpt(rcpt); err != nil {
+ return wrapSendError("RCPT TO", rcpt, fmt.Errorf("SMTP RCPT TO failed: %w", err))
}
}
w, err := client.Data()
if err != nil {
- return fmt.Errorf("SMTP DATA failed: %w", err)
+ return wrapSendError("DATA", "", fmt.Errorf("SMTP DATA failed: %w", err))
}
if _, err := w.Write(msg); err != nil {
return fmt.Errorf("SMTP write failed: %w", err)
}
if err := w.Close(); err != nil {
- return fmt.Errorf("SMTP close failed: %w", err)
+ return wrapSendError("DATA", "", fmt.Errorf("SMTP close failed: %w", err))
}
return client.Quit()
}
+// wrapSendError turns a stage failure into a *SendError carrying the SMTP reply
+// code and recipient, while preserving the original error string.
+func wrapSendError(stage, recipient string, err error) error {
+ code, msg := smtpReply(err)
+ return &SendError{Stage: stage, Recipient: recipient, Code: code, Msg: msg, Err: err}
+}
+
func buildMessage(from string, to []string, subject, htmlBody, textBody string, attachments []models.Attachment, headers map[string]string, listUnsubscribeURL string, listUnsubscribePost bool) []byte {
var b strings.Builder
diff --git a/internal/services/email/smtp_sender_test.go b/internal/services/email/smtp_sender_test.go
new file mode 100644
index 0000000..9d7a4ea
--- /dev/null
+++ b/internal/services/email/smtp_sender_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
+ */
+
+package email
+
+import (
+ "errors"
+ "fmt"
+ "net/textproto"
+ "testing"
+)
+
+func TestSmtpReply(t *testing.T) {
+ // A *textproto.Error wrapped the way the net/smtp client surfaces a 550.
+ rcptErr := fmt.Errorf("SMTP RCPT TO failed: %w", &textproto.Error{
+ Code: 550,
+ Msg: "5.1.1 <[email protected]>: Recipient address rejected: User unknown",
+ })
+ code, msg := smtpReply(rcptErr)
+ if code != 550 {
+ t.Fatalf("smtpReply code = %d, want 550", code)
+ }
+ if msg == "" {
+ t.Fatalf("smtpReply msg is empty, want server text")
+ }
+
+ // A plain connection error carries no SMTP reply code.
+ if code, _ := smtpReply(errors.New("dial tcp: connection refused")); code != 0 {
+ t.Fatalf("smtpReply code = %d for non-SMTP error, want 0", code)
+ }
+}
+
+func TestSendErrorPermanent(t *testing.T) {
+ cases := []struct {
+ code int
+ want bool
+ }{
+ {550, true},
+ {551, true},
+ {554, true},
+ {450, false}, // transient
+ {421, false}, // transient
+ {0, false}, // connection-level
+ {250, false},
+ }
+ for _, c := range cases {
+ se := &SendError{Code: c.code, Err: errors.New("x")}
+ if got := se.Permanent(); got != c.want {
+ t.Errorf("SendError{Code:%d}.Permanent() = %v, want %v", c.code, got, c.want)
+ }
+ }
+}
+
+func TestWrapSendError(t *testing.T) {
+ orig := fmt.Errorf("SMTP RCPT TO failed: %w", &textproto.Error{Code: 550, Msg: "5.1.1 rejected"})
+ err := wrapSendError("RCPT TO", "[email protected]", orig)
+
+ var se *SendError
+ if !errors.As(err, &se) {
+ t.Fatalf("wrapSendError result is not a *SendError")
+ }
+ if se.Stage != "RCPT TO" || se.Recipient != "[email protected]" || se.Code != 550 {
+ t.Fatalf("unexpected SendError: %+v", se)
+ }
+ if !se.Permanent() {
+ t.Fatalf("550 should be permanent")
+ }
+ // Error string must be preserved unchanged for storage/logging.
+ if se.Error() != orig.Error() {
+ t.Fatalf("Error() = %q, want %q", se.Error(), orig.Error())
+ }
+}
diff --git a/internal/worker/handler.go b/internal/worker/handler.go
index 0fa095b..a760839 100644
--- a/internal/worker/handler.go
+++ b/internal/worker/handler.go
@@ -21,12 +21,14 @@ import (
"context"
"encoding/base64"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/mail"
"strings"
"time"
+ "github.com/goposta/posta/internal/metrics"
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/email"
"github.com/goposta/posta/internal/services/webhook"
@@ -38,19 +40,22 @@ import (
// EmailSendHandler processes email:send tasks from the Asynq queue.
type EmailSendHandler struct {
- emailRepo *repositories.EmailRepository
- smtpRepo *repositories.SMTPRepository
- serverRepo *repositories.ServerRepository
- domainRepo *repositories.DomainRepository
- contactRepo *repositories.ContactRepository
- messageRepo *repositories.CampaignMessageRepository
- campaignRepo *repositories.CampaignRepository
- sender *email.SMTPSender
- stamper *email.Stamper
- dispatcher *webhook.Dispatcher
- blobStore blob.Store
- onSent func()
- onFailed func()
+ emailRepo *repositories.EmailRepository
+ smtpRepo *repositories.SMTPRepository
+ serverRepo *repositories.ServerRepository
+ domainRepo *repositories.DomainRepository
+ contactRepo *repositories.ContactRepository
+ messageRepo *repositories.CampaignMessageRepository
+ campaignRepo *repositories.CampaignRepository
+ suppressionRepo *repositories.SuppressionRepository
+ bounceRepo *repositories.BounceRepository
+ autoSuppress bool
+ sender *email.SMTPSender
+ stamper *email.Stamper
+ dispatcher *webhook.Dispatcher
+ blobStore blob.Store
+ onSent func()
+ onFailed func()
}
func NewEmailSendHandler(
@@ -94,6 +99,24 @@ func (h *EmailSendHandler) SetStamper(s *email.Stamper) {
h.stamper = s
}
+// SetSuppressionRepo enables auto-suppression of recipients permanently
+// rejected by the receiving server.
+func (h *EmailSendHandler) SetSuppressionRepo(r *repositories.SuppressionRepository) {
+ h.suppressionRepo = r
+}
+
+// SetBounceRepo lets the handler record a hard bounce when a recipient is
+// permanently rejected.
+func (h *EmailSendHandler) SetBounceRepo(r *repositories.BounceRepository) {
+ h.bounceRepo = r
+}
+
+// SetAutoSuppress toggles auto-suppression on permanent (5xx) recipient
+// rejection. When false, such failures fall back to the normal retry path.
+func (h *EmailSendHandler) SetAutoSuppress(enabled bool) {
+ h.autoSuppress = enabled
+}
+
// OnSent sets a callback invoked after each successful email send.
func (h *EmailSendHandler) OnSent(fn func()) { h.onSent = fn }
@@ -243,6 +266,27 @@ func (h *EmailSendHandler) ProcessTask(ctx context.Context, t *asynq.Task) error
headers = make(map[string]string)
}
+ // Drop recipients that became suppressed since this email was enqueued
+ recipients := []string(em.Recipients)
+ if h.suppressionRepo != nil {
+ scope := repositories.ResourceScope{UserID: em.UserID, WorkspaceID: em.WorkspaceID}
+ if filtered, fErr := h.suppressionRepo.FilterSuppressed(scope, recipients); fErr == nil {
+ if len(filtered) == 0 {
+ em.Status = models.EmailStatusSuppressed
+ em.ErrorMessage = "all recipients are suppressed"
+ _ = h.emailRepo.Update(em)
+ if h.messageRepo != nil {
+ if msg, mErr := h.messageRepo.FindByEmailID(em.ID); mErr == nil {
+ _ = h.messageRepo.UpdateStatus(msg.ID, models.CampaignMsgSkipped, "recipient suppressed")
+ }
+ }
+ logger.Info("worker: skipping email, all recipients suppressed", "id", em.ID)
+ return nil
+ }
+ recipients = filtered
+ }
+ }
+
// Stamp Posta headers. Campaign mail gets campaign-aware headers; everything
// else gets transactional headers. A final HMAC signs the message identity.
if h.stamper != nil {
@@ -263,18 +307,28 @@ func (h *EmailSendHandler) ProcessTask(ctx context.Context, t *asynq.Task) error
} else {
h.stamper.StampTransactional(headers, em)
}
- h.stamper.Sign(headers, em, em.Recipients, em.Subject)
+ h.stamper.Sign(headers, em, recipients, em.Subject)
}
- if err := h.sender.Send(smtpServer, em.Sender, em.Recipients, em.Subject, em.HTMLBody, em.TextBody, attachments, headers, em.ListUnsubscribeURL, em.ListUnsubscribePost); err != nil {
+ if err := h.sender.Send(smtpServer, em.Sender, recipients, em.Subject, em.HTMLBody, em.TextBody, attachments, headers, em.ListUnsubscribeURL, em.ListUnsubscribePost); err != nil {
+ // Increment the shared server's failure counter regardless of outcome.
+ if sharedServerID != 0 && h.serverRepo != nil {
+ go h.serverRepo.IncrementFailedCount(sharedServerID)
+ }
+
+ // A permanent rejection at RCPT TO (5xx, e.g. 550 user unknown) is a
+ // hard bounce: suppress the recipient and stop retrying — retrying a
+ // 5xx is pointless.
+ if se, ok := permanentRejection(err); ok && h.autoSuppress {
+ h.handlePermanentRejection(em, se)
+ logger.Info("worker: recipient permanently rejected, suppressed", "id", em.ID, "recipient", se.Recipient, "code", se.Code)
+ return nil
+ }
+
em.RetryCount++
em.Status = models.EmailStatusFailed
em.ErrorMessage = err.Error()
_ = h.emailRepo.Update(em)
- // Increment the shared server's failure counter
- if sharedServerID != 0 && h.serverRepo != nil {
- go h.serverRepo.IncrementFailedCount(sharedServerID)
- }
logger.Debug("worker: email send failed, will retry", "id", em.ID, "attempt", em.RetryCount, "error", err)
// Return error so Asynq retries the task
return fmt.Errorf("SMTP send failed: %w", err)
@@ -295,7 +349,7 @@ func (h *EmailSendHandler) ProcessTask(ctx context.Context, t *asynq.Task) error
h.onSent()
}
if h.contactRepo != nil {
- go h.contactRepo.RecordSent(em.UserID, em.WorkspaceID, em.Recipients)
+ go h.contactRepo.RecordSent(em.UserID, em.WorkspaceID, recipients)
}
if h.messageRepo != nil {
if msg, err := h.messageRepo.FindByEmailID(em.ID); err == nil {
@@ -325,6 +379,74 @@ func (h *EmailSendHandler) markFailed(em *models.Email, reason string) {
}
}
+// permanentRejection reports whether err represents a permanent recipient
+// rejection (a 5xx reply at RCPT TO, e.g. 550 user unknown) that should trigger
+// auto-suppression. Transient errors (4xx), connection failures, and failures
+// at other SMTP stages (MAIL FROM, DATA) return false so they keep retrying.
+func permanentRejection(err error) (*email.SendError, bool) {
+ var se *email.SendError
+ if errors.As(err, &se) && se.Permanent() && se.Stage == "RCPT TO" && se.Recipient != "" {
+ return se, true
+ }
+ return nil, false
+}
+
+// handlePermanentRejection records a hard bounce, adds the recipient to the
+// suppression list (idempotently) and marks the email failed without retrying.
+// Called when the receiving server permanently rejects a recipient (5xx at
+// RCPT TO, e.g. 550 user unknown).
+func (h *EmailSendHandler) handlePermanentRejection(em *models.Email, se *email.SendError) {
+ reason := se.Msg
+ if reason == "" {
+ reason = se.Error()
+ }
+
+ // Record a hard bounce for audit/metrics.
+ if h.bounceRepo != nil {
+ bounce := &models.Bounce{
+ UserID: em.UserID,
+ WorkspaceID: em.WorkspaceID,
+ EmailID: em.ID,
+ Recipient: se.Recipient,
+ Type: models.BounceTypeHard,
+ Reason: reason,
+ }
+ if err := h.bounceRepo.Create(bounce); err == nil {
+ metrics.IncrementBounce(string(models.BounceTypeHard))
+ }
+ }
+
+ // Add to the suppression list (idempotent — ignore "already suppressed").
+ if h.suppressionRepo != nil {
+ suppression := &models.Suppression{
+ UserID: em.UserID,
+ WorkspaceID: em.WorkspaceID,
+ Email: se.Recipient,
+ Reason: fmt.Sprintf("auto-suppressed: SMTP %d %s", se.Code, reason),
+ }
+ if err := h.suppressionRepo.Upsert(suppression); err == nil {
+ metrics.IncrementSuppression()
+ }
+ }
+
+ em.Status = models.EmailStatusFailed
+ em.ErrorMessage = se.Error()
+ _ = h.emailRepo.Update(em)
+
+ h.dispatcher.Dispatch(em.UserID, "email.failed", em.UUID, em.Sender)
+ if h.onFailed != nil {
+ h.onFailed()
+ }
+ if h.contactRepo != nil {
+ go h.contactRepo.RecordFailed(em.UserID, em.WorkspaceID, em.Recipients)
+ }
+ if h.messageRepo != nil {
+ if msg, err := h.messageRepo.FindByEmailID(em.ID); err == nil {
+ _ = h.messageRepo.UpdateStatus(msg.ID, models.CampaignMsgFailed, reason)
+ }
+ }
+}
+
// senderDomain extracts the domain part of an email address.
func senderDomain(addr string) string {
parts := strings.SplitN(addr, "@", 2)
diff --git a/internal/worker/handler_test.go b/internal/worker/handler_test.go
new file mode 100644
index 0000000..c6cb698
--- /dev/null
+++ b/internal/worker/handler_test.go
@@ -0,0 +1,71 @@
+/*
+ * 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
+ */
+
+package worker
+
+import (
+ "errors"
+ "fmt"
+ "net/textproto"
+ "testing"
+
+ "github.com/goposta/posta/internal/services/email"
+)
+
+// smtpErr builds the kind of wrapped *textproto.Error the net/smtp client
+// surfaces, matching how email.sendViaClient wraps RCPT/MAIL/DATA failures.
+func smtpErr(stage, recipient string, code int) error {
+ inner := fmt.Errorf("SMTP %s failed: %w", stage, &textproto.Error{Code: code, Msg: "5.1.1 rejected"})
+ return &email.SendError{Stage: stage, Recipient: recipient, Code: code, Msg: "5.1.1 rejected", Err: inner}
+}
+
+func TestPermanentRejection(t *testing.T) {
+ cases := []struct {
+ name string
+ err error
+ want bool
+ }{
+ {"550 at RCPT TO", smtpErr("RCPT TO", "[email protected]", 550), true},
+ {"554 at RCPT TO", smtpErr("RCPT TO", "[email protected]", 554), true},
+ {"450 transient at RCPT TO", smtpErr("RCPT TO", "[email protected]", 450), false},
+ {"550 at MAIL FROM (sender-side)", smtpErr("MAIL FROM", "", 550), false},
+ {"550 at DATA (content/policy)", smtpErr("DATA", "", 550), false},
+ {"plain connection error", errors.New("dial tcp: connection refused"), false},
+ {"wrapped send error", fmt.Errorf("SMTP send failed: %w", smtpErr("RCPT TO", "[email protected]", 550)), true},
+ }
+
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ se, ok := permanentRejection(c.err)
+ if ok != c.want {
+ t.Fatalf("permanentRejection() ok = %v, want %v", ok, c.want)
+ }
+ if ok && se == nil {
+ t.Fatalf("permanentRejection() returned ok with nil SendError")
+ }
+ if !ok && se != nil {
+ t.Fatalf("permanentRejection() returned !ok with non-nil SendError")
+ }
+ })
+ }
+}
+
+func TestPermanentRejectionExposesRecipient(t *testing.T) {
+ se, ok := permanentRejection(fmt.Errorf("SMTP send failed: %w", smtpErr("RCPT TO", "[email protected]", 550)))
+ if !ok {
+ t.Fatal("expected permanent rejection")
+ }
+ if se.Recipient != "[email protected]" {
+ t.Fatalf("recipient = %q, want [email protected]", se.Recipient)
+ }
+ if se.Code != 550 {
+ t.Fatalf("code = %d, want 550", se.Code)
+ }
+}