Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(email): per-list transactional unsubscribe + scoped suppression
Jonas Kanindad39cc702f4a4
diff --git a/README.md b/README.mdindex 98a077e..d436f96 100644--- a/README.md+++ b/README.md@@ -41,7 +41,7 @@ curl -X POST http://localhost:9000/api/v1/emails/send \-H "Content-Type: application/json" \-d '{"from": "Acme <[email protected]>",- "to": ["[email protected]"],+ "to": ["Jonas Kaninda <[email protected]>","[email protected]"],"subject": "Hello from Posta","html": "<h1>Hello!</h1>"}'@@ -116,6 +116,15 @@ Response:* Hard/soft bounce and complaint handling* Automatic suppression lists+### Unsubscribe Lists++* RFC 8058 one-click unsubscribe scoped per list+* Posta-minted signed URLs and `List-Unsubscribe` header+* Scoped opt-outs so receipts and password resets keep flowing+* Management API and dashboard for CRUD and opt-out browsing+* `email.unsubscribed` webhook event+* Resubscribe individual addresses without lifting a global block+### Tracking* Pixel-based open trackingdiff --git a/docs/static/img/screenshots/dashboard.png b/docs/static/img/screenshots/dashboard.pngindex d23a266..f0fb531 100644Binary files a/docs/static/img/screenshots/dashboard.png and b/docs/static/img/screenshots/dashboard.png differdiff --git a/internal/handlers/bounce_handler.go b/internal/handlers/bounce_handler.goindex 4517c38..2276d71 100644--- a/internal/handlers/bounce_handler.go+++ b/internal/handlers/bounce_handler.go@@ -18,8 +18,12 @@package handlersimport (+ "encoding/json"+ "time"+"github.com/goposta/posta/internal/metrics""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/webhook""github.com/goposta/posta/internal/storage/repositories""github.com/jkaninda/okapi")@@ -34,6 +38,7 @@ type BounceHandler struct {bounceRepo *repositories.BounceRepositorysuppressionRepo *repositories.SuppressionRepositoryemailRepo *repositories.EmailRepository+ dispatcher *webhook.Dispatcher}type RecordBounceRequest struct {Body struct {@@ -44,8 +49,8 @@ type RecordBounceRequest struct {} `json:"body"`}-func NewBounceHandler(bounceRepo *repositories.BounceRepository, suppressionRepo *repositories.SuppressionRepository, emailRepo *repositories.EmailRepository) *BounceHandler {- return &BounceHandler{bounceRepo: bounceRepo, suppressionRepo: suppressionRepo, emailRepo: emailRepo}+func NewBounceHandler(bounceRepo *repositories.BounceRepository, suppressionRepo *repositories.SuppressionRepository, emailRepo *repositories.EmailRepository, dispatcher *webhook.Dispatcher) *BounceHandler {+ return &BounceHandler{bounceRepo: bounceRepo, suppressionRepo: suppressionRepo, emailRepo: emailRepo, dispatcher: dispatcher}}func (h *BounceHandler) Record(c *okapi.Context, req *RecordBounceRequest) error {@@ -79,12 +84,18 @@ func (h *BounceHandler) Record(c *okapi.Context, req *RecordBounceRequest) errormetrics.IncrementBounce(req.Body.Type)- // Auto-suppress on hard bounce or complaint+ // Auto-suppress on hard bounce or complaint. Kind is set explicitly so the+ // row is distinguishable from a manual block in the suppression table.if req.Body.Type == bounceTypeHard || req.Body.Type == bounceTypeComplaint {+ kind := models.SuppressionKindBounce+ if req.Body.Type == bounceTypeComplaint {+ kind = models.SuppressionKindComplaint+ }suppression := &models.Suppression{UserID: scope.UserID,WorkspaceID: scope.WorkspaceID,Email: req.Body.Recipient,+ Kind: kind,Reason: "auto-suppressed: " + req.Body.Type + " bounce",}// Ignore error if already suppressed@@ -93,9 +104,38 @@ func (h *BounceHandler) Record(c *okapi.Context, req *RecordBounceRequest) error}}+ // Complaint webhook: high-value signal for senders to mirror into their own+ // CRM. Mirrors the email.unsubscribed payload shape.+ if req.Body.Type == bounceTypeComplaint {+ h.emitComplained(em, req.Body.Recipient)+ }+return created(c, bounce)}+// emitComplained fires the email.complained webhook for a recorded complaint.+func (h *BounceHandler) emitComplained(em *models.Email, addr string) {+ if h.dispatcher == nil {+ return+ }+ payload := struct {+ Event string `json:"event"`+ EmailUUID string `json:"email_uuid"`+ Email string `json:"email"`+ Timestamp string `json:"timestamp"`+ }{+ Event: "email.complained",+ EmailUUID: em.UUID,+ Email: addr,+ Timestamp: time.Now().UTC().Format(time.RFC3339),+ }+ body, err := json.Marshal(payload)+ if err != nil {+ return+ }+ h.dispatcher.DispatchJSON(em.UserID, em.WorkspaceID, "email.complained", body, em.Sender)+}+func (h *BounceHandler) List(c *okapi.Context, req *ListRequest) error {page, size, offset := normalizePageParams(req.Page, req.Size)diff --git a/internal/handlers/email_handler.go b/internal/handlers/email_handler.goindex b22df99..c63c18e 100644--- a/internal/handlers/email_handler.go+++ b/internal/handlers/email_handler.go@@ -18,6 +18,7 @@package handlersimport (+ "errors""fmt""strings"@@ -137,6 +138,10 @@ func (h *EmailHandler) Send(c *okapi.Context, req *SendEmailRequest) error {apiKeyID := c.GetInt("api_key_id")resp, err := h.service.Send(c.Request().Context(), uint(userID), uint(apiKeyID), scope.WorkspaceID, userEmail, &req.Body)if err != nil {+ if resp := mapUnsubscribeError(c, err); resp != nil {+ // Call abort here+ return resp+ }if isRateLimitError(err) {return c.AbortTooManyRequests(err.Error())}@@ -162,6 +167,9 @@ func (h *EmailHandler) Send(c *okapi.Context, req *SendEmailRequest) error {func (h *EmailHandler) handleDryRun(c *okapi.Context, userID int, workspaceID *uint, userEmail string, req *SendEmailRequest) error {resp, err := h.service.ValidateSend(c.Request().Context(), uint(userID), workspaceID, userEmail, &req.Body)if err != nil {+ if resp := mapUnsubscribeError(c, err); resp != nil {+ return resp+ }if isRateLimitError(err) {return c.AbortTooManyRequests(err.Error())}@@ -184,6 +192,9 @@ func (h *EmailHandler) SendWithTemplate(c *okapi.Context, req *SendTemplateEmailif req.DryRun {resp, err := h.service.ValidateSendWithTemplate(c.Request().Context(), uint(userID), scope.WorkspaceID, userEmail, &req.Body)if err != nil {+ if resp := mapUnsubscribeError(c, err); resp != nil {+ return resp+ }if isRateLimitError(err) {return c.AbortTooManyRequests(err.Error())}@@ -198,6 +209,9 @@ func (h *EmailHandler) SendWithTemplate(c *okapi.Context, req *SendTemplateEmailapiKeyID := c.GetInt("api_key_id")resp, err := h.service.SendWithTemplate(c.Request().Context(), uint(userID), uint(apiKeyID), scope.WorkspaceID, userEmail, &req.Body)if err != nil {+ if resp := mapUnsubscribeError(c, err); resp != nil {+ return resp+ }if isRateLimitError(err) {return c.AbortTooManyRequests(err.Error())}@@ -230,6 +244,9 @@ func (h *EmailHandler) SendBatch(c *okapi.Context, req *SendBatchEmailRequest) eif req.DryRun {resp, err := h.service.ValidateSendBatch(c.Request().Context(), uint(userID), scope.WorkspaceID, userEmail, &req.Body)if err != nil {+ if resp := mapUnsubscribeError(c, err); resp != nil {+ return resp+ }if isRateLimitError(err) {return c.AbortTooManyRequests(err.Error())}@@ -241,6 +258,9 @@ func (h *EmailHandler) SendBatch(c *okapi.Context, req *SendBatchEmailRequest) eapiKeyID := c.GetInt("api_key_id")resp, err := h.service.SendBatch(c.Request().Context(), uint(userID), uint(apiKeyID), scope.WorkspaceID, userEmail, &req.Body)if err != nil {+ if resp := mapUnsubscribeError(c, err); resp != nil {+ return resp+ }if isRateLimitError(err) {return c.AbortTooManyRequests(err.Error())}@@ -380,3 +400,13 @@ func isRateLimitError(err error) bool {func isDomainVerificationError(err error) bool {return err != nil && strings.HasPrefix(err.Error(), "domain_verification:")}++func mapUnsubscribeError(c *okapi.Context, err error) error {+ if errors.Is(err, email.ErrUnsubscribeListNotFound) {+ return c.AbortNotFound(err.Error())+ }+ if errors.Is(err, email.ErrUnsubscribeInvalid) {+ return c.AbortBadRequest(err.Error())+ }+ return nil+}diff --git a/internal/handlers/suppression_handler.go b/internal/handlers/suppression_handler.goindex 24e4c0d..90010a6 100644--- a/internal/handlers/suppression_handler.go+++ b/internal/handlers/suppression_handler.go@@ -24,22 +24,31 @@ import ()type SuppressionHandler struct {- repo *repositories.SuppressionRepository+ repo *repositories.SuppressionRepository+ unsubRepo *repositories.UnsubscribeListRepository}type CreateSuppressionRequest struct {Body struct {Email string `json:"email" required:"true" format:"email"`Reason string `json:"reason"`+ // ListID scopes the suppression to one UnsubscribeList. Omit for a global block.+ ListID *uint `json:"list_id,omitempty"`} `json:"body"`}+type ListSuppressionsRequest struct {+ Page int `query:"page" default:"0"`+ Size int `query:"size" default:"20"`+ ListID uint `query:"list_id" default:"0"`+}type DeleteSuppressionRequest struct {Body struct {- Email string `json:"email" required:"true" format:"email"`+ Email string `json:"email" required:"true" format:"email"`+ ListID *uint `json:"list_id,omitempty"`} `json:"body"`}-func NewSuppressionHandler(repo *repositories.SuppressionRepository) *SuppressionHandler {- return &SuppressionHandler{repo: repo}+func NewSuppressionHandler(repo *repositories.SuppressionRepository, unsubRepo *repositories.UnsubscribeListRepository) *SuppressionHandler {+ return &SuppressionHandler{repo: repo, unsubRepo: unsubRepo}}func (h *SuppressionHandler) Create(c *okapi.Context, req *CreateSuppressionRequest) error {@@ -48,10 +57,22 @@ func (h *SuppressionHandler) Create(c *okapi.Context, req *CreateSuppressionRequ}scope := getScope(c)+ // A list-scoped suppression must reference a list the caller owns.+ if req.Body.ListID != nil {+ if h.unsubRepo == nil {+ return c.AbortBadRequest("list-scoped suppression is not available")+ }+ if _, err := h.unsubRepo.FindByIDForScope(*req.Body.ListID, scope); err != nil {+ return c.AbortNotFound("unsubscribe list not found")+ }+ }+suppression := &models.Suppression{UserID: scope.UserID,WorkspaceID: scope.WorkspaceID,Email: req.Body.Email,+ ListID: req.Body.ListID,+ Kind: models.SuppressionKindManual,Reason: req.Body.Reason,}@@ -62,10 +83,15 @@ func (h *SuppressionHandler) Create(c *okapi.Context, req *CreateSuppressionRequreturn created(c, suppression)}-func (h *SuppressionHandler) List(c *okapi.Context, req *ListRequest) error {+func (h *SuppressionHandler) List(c *okapi.Context, req *ListSuppressionsRequest) error {page, size, offset := normalizePageParams(req.Page, req.Size)- suppressions, total, err := h.repo.FindByScope(getScope(c), size, offset)+ var listID *uint+ if req.ListID > 0 {+ listID = &req.ListID+ }++ suppressions, total, err := h.repo.FindByScopeFiltered(getScope(c), listID, size, offset)if err != nil {return c.AbortInternalServerError("failed to list suppressions")}@@ -79,7 +105,7 @@ func (h *SuppressionHandler) Delete(c *okapi.Context, req *DeleteSuppressionRequ}scope := getScope(c)- if err := h.repo.Delete(scope, req.Body.Email); err != nil {+ if err := h.repo.Delete(scope, req.Body.Email, req.Body.ListID); err != nil {return c.AbortInternalServerError("failed to remove from suppression list")}diff --git a/internal/handlers/tracking_handler.go b/internal/handlers/tracking_handler.goindex c1aa24f..648f37f 100644--- a/internal/handlers/tracking_handler.go+++ b/internal/handlers/tracking_handler.go@@ -18,6 +18,7 @@package handlersimport (+ "encoding/json""fmt""html""net/http"@@ -27,6 +28,7 @@ import ("github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/tracking"+ "github.com/goposta/posta/internal/services/webhook""github.com/goposta/posta/internal/storage/repositories""github.com/jkaninda/okapi")@@ -45,6 +47,7 @@ type TrackingHandler struct {emailRepo *repositories.EmailRepositorysuppressionRepo *repositories.SuppressionRepositorytrackingService *tracking.Service+ dispatcher *webhook.Dispatcher}func NewTrackingHandler(@@ -56,6 +59,7 @@ func NewTrackingHandler(emailRepo *repositories.EmailRepository,suppressionRepo *repositories.SuppressionRepository,trackingService *tracking.Service,+ dispatcher *webhook.Dispatcher,) *TrackingHandler {return &TrackingHandler{trackingRepo: trackingRepo,@@ -66,6 +70,7 @@ func NewTrackingHandler(emailRepo: emailRepo,suppressionRepo: suppressionRepo,trackingService: trackingService,+ dispatcher: dispatcher,}}@@ -204,6 +209,12 @@ func (h *TrackingHandler) TxUnsubscribeConfirm(c *okapi.Context, req *TrackingUn}if h.suppressionRepo != nil {+ // A Posta-minted link carries a list ⇒ scoped opt-out. A nil list means a+ // legacy link, which keeps the old global behavior.+ kind := models.SuppressionKindHard+ if em.UnsubscribeListID != nil {+ kind = models.SuppressionKindListUnsubscribe+ }for _, addr := range em.Recipients {if addr == "" {continue@@ -212,8 +223,11 @@ func (h *TrackingHandler) TxUnsubscribeConfirm(c *okapi.Context, req *TrackingUnUserID: em.UserID,WorkspaceID: em.WorkspaceID,Email: addr,+ ListID: em.UnsubscribeListID,+ Kind: kind,Reason: "one_click_unsubscribe",})+ h.emitUnsubscribed(em, addr)}}@@ -226,6 +240,33 @@ h1{font-size:20px;color:#16a34a}p{color:#6b7280;font-size:14px}</style></head><breturn c.HTMLView(http.StatusOK, confirmHTML, okapi.M{})}+// emitUnsubscribed fires the email.unsubscribed webhook for a one-click opt-out.+// It uses DispatchJSON because the payload is richer than the standard outbound+// {event, email_id} shape — it carries the recipient and the scoped list.+func (h *TrackingHandler) emitUnsubscribed(em *models.Email, addr string) {+ if h.dispatcher == nil {+ return+ }+ payload := struct {+ Event string `json:"event"`+ EmailUUID string `json:"email_uuid"`+ Email string `json:"email"`+ ListID *uint `json:"list_id,omitempty"`+ Timestamp string `json:"timestamp"`+ }{+ Event: "email.unsubscribed",+ EmailUUID: em.UUID,+ Email: addr,+ ListID: em.UnsubscribeListID,+ Timestamp: time.Now().UTC().Format(time.RFC3339),+ }+ body, err := json.Marshal(payload)+ if err != nil {+ return+ }+ h.dispatcher.DispatchJSON(em.UserID, em.WorkspaceID, "email.unsubscribed", body, em.Sender)+}+// WebView renders a hosted copy of a sent email ("view in browser"). The token is// an HMAC-signed, expiring capability bound to the email's opaque UUID. Because the// page renders arbitrary customer HTML, it is served with a restrictive CSP, nodiff --git a/internal/handlers/unsubscribe_list_handler.go b/internal/handlers/unsubscribe_list_handler.gonew file mode 100644index 0000000..374a4f9--- /dev/null+++ b/internal/handlers/unsubscribe_list_handler.go@@ -0,0 +1,144 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package handlers++import (+ "time"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/okapi"+)++// UnsubscribeListHandler is the scoped CRUD API for transactional unsubscribe+// lists. A send references one of these by id so Posta can mint a one-click link+// whose click suppresses the recipient on that list only.+type UnsubscribeListHandler struct {+ repo *repositories.UnsubscribeListRepository+}++func NewUnsubscribeListHandler(repo *repositories.UnsubscribeListRepository) *UnsubscribeListHandler {+ return &UnsubscribeListHandler{repo: repo}+}++type CreateUnsubscribeListRequest struct {+ Body struct {+ Name string `json:"name" required:"true"`+ PublicName string `json:"public_name"`+ Description string `json:"description"`+ } `json:"body"`+}++type UpdateUnsubscribeListRequest struct {+ ID int `param:"id"`+ Body struct {+ Name string `json:"name"`+ PublicName string `json:"public_name"`+ Description string `json:"description"`+ Active *bool `json:"active"`+ } `json:"body"`+}++type GetUnsubscribeListRequest struct {+ ID int `param:"id"`+}++type DeleteUnsubscribeListRequest struct {+ ID int `param:"id"`+}++func (h *UnsubscribeListHandler) Create(c *okapi.Context, req *CreateUnsubscribeListRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("Insufficient workspace permissions", err)+ }+ scope := getScope(c)++ list := &models.UnsubscribeList{+ UserID: scope.UserID,+ WorkspaceID: scope.WorkspaceID,+ Name: req.Body.Name,+ PublicName: req.Body.PublicName,+ Description: req.Body.Description,+ Active: true,+ }+ if err := h.repo.Create(list); err != nil {+ return c.AbortConflict("an unsubscribe list with that name already exists")+ }+ return created(c, list)+}++func (h *UnsubscribeListHandler) List(c *okapi.Context, req *ListRequest) error {+ page, size, offset := normalizePageParams(req.Page, req.Size)+ lists, total, err := h.repo.FindByScope(getScope(c), size, offset)+ if err != nil {+ return c.AbortInternalServerError("failed to list unsubscribe lists")+ }+ return paginated(c, lists, total, page, size)+}++func (h *UnsubscribeListHandler) Get(c *okapi.Context, req *GetUnsubscribeListRequest) error {+ list, err := h.repo.FindByID(uint(req.ID))+ if err != nil || !ownsResource(c, list.UserID, list.WorkspaceID) {+ return c.AbortNotFound("unsubscribe list not found")+ }+ return ok(c, list)+}++func (h *UnsubscribeListHandler) Update(c *okapi.Context, req *UpdateUnsubscribeListRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("Insufficient workspace permissions", err)+ }+ list, err := h.repo.FindByID(uint(req.ID))+ if err != nil || !ownsResource(c, list.UserID, list.WorkspaceID) {+ return c.AbortNotFound("unsubscribe list not found")+ }++ if req.Body.Name != "" {+ list.Name = req.Body.Name+ }+ if req.Body.PublicName != "" {+ list.PublicName = req.Body.PublicName+ }+ if req.Body.Description != "" {+ list.Description = req.Body.Description+ }+ if req.Body.Active != nil {+ list.Active = *req.Body.Active+ }+ now := time.Now()+ list.UpdatedAt = &now++ if err := h.repo.Update(list); err != nil {+ return c.AbortInternalServerError("failed to update unsubscribe list")+ }+ return ok(c, list)+}++func (h *UnsubscribeListHandler) Delete(c *okapi.Context, req *DeleteUnsubscribeListRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("Insufficient workspace permissions", err)+ }+ list, err := h.repo.FindByID(uint(req.ID))+ if err != nil || !ownsResource(c, list.UserID, list.WorkspaceID) {+ return c.AbortNotFound("unsubscribe list not found")+ }+ if err := h.repo.Delete(list.ID); err != nil {+ return c.AbortInternalServerError("failed to delete unsubscribe list")+ }+ return noContent(c)+}diff --git a/internal/handlers/webhook_handler.go b/internal/handlers/webhook_handler.goindex 6e2464f..dae876a 100644--- a/internal/handlers/webhook_handler.go+++ b/internal/handlers/webhook_handler.go@@ -34,7 +34,7 @@ type WebhookHandler struct {type CreateWebhookRequest struct {Body struct {URL string `json:"url" required:"true" format:"url"`- Events []string `json:"events" required:"true" minItems:"1" enum:"email.sent,email.failed,email.inbound,campaign.started,campaign.completed"`+ Events []string `json:"events" required:"true" minItems:"1" enum:"email.sent,email.failed,email.inbound,email.unsubscribed,email.complained,campaign.started,campaign.completed"`Filters []string `json:"filters"`} `json:"body"`}diff --git a/internal/models/email.go b/internal/models/email.goindex cbfb743..4ff454d 100644--- a/internal/models/email.go+++ b/internal/models/email.go@@ -36,28 +36,32 @@ const ()type Email struct {- ID uint `json:"id" gorm:"primaryKey"`- UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`- UserID uint `json:"user_id" gorm:"index;not null"`- WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`- APIKeyID *uint `json:"api_key_id" gorm:"index"`- Sender string `json:"sender" gorm:"not null"`- Recipients pq.StringArray `json:"recipients" gorm:"type:text[];not null"`- Subject string `json:"subject" gorm:"not null"`- TemplateName string `json:"template_name,omitempty"`- HTMLBody string `json:"html_body"`- TextBody string `json:"text_body"`- AttachmentsJSON string `json:"attachments_json,omitempty" gorm:"type:text"`- HeadersJSON string `json:"headers_json,omitempty" gorm:"type:text"`- ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty" gorm:"type:text"`- ListUnsubscribePost bool `json:"list_unsubscribe_post,omitempty"`- Status EmailStatus `json:"status" gorm:"default:pending;not null"`- ErrorMessage string `json:"error_message"`- RetryCount int `json:"retry_count" gorm:"default:0;not null"`- CreatedAt time.Time `json:"created_at"`- SentAt *time.Time `json:"sent_at"`- ScheduledAt *time.Time `json:"scheduled_at"`- Provider string `json:"provider,omitempty" gorm:"index;size:32"`+ ID uint `json:"id" gorm:"primaryKey"`+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`+ UserID uint `json:"user_id" gorm:"index;not null"`+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`+ APIKeyID *uint `json:"api_key_id" gorm:"index"`+ Sender string `json:"sender" gorm:"not null"`+ Recipients pq.StringArray `json:"recipients" gorm:"type:text[];not null"`+ Subject string `json:"subject" gorm:"not null"`+ TemplateName string `json:"template_name,omitempty"`+ HTMLBody string `json:"html_body"`+ TextBody string `json:"text_body"`+ AttachmentsJSON string `json:"attachments_json,omitempty" gorm:"type:text"`+ HeadersJSON string `json:"headers_json,omitempty" gorm:"type:text"`+ ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty" gorm:"type:text"`+ ListUnsubscribeMailto string `json:"list_unsubscribe_mailto,omitempty" gorm:"type:text"`+ ListUnsubscribePost bool `json:"list_unsubscribe_post,omitempty"`+ // UnsubscribeListID scopes a one-click unsubscribe to a single UnsubscribeList.+ // nil ⇒ a click suppresses globally (legacy links only).+ UnsubscribeListID *uint `json:"unsubscribe_list_id,omitempty" gorm:"index"`+ Status EmailStatus `json:"status" gorm:"default:pending;not null"`+ ErrorMessage string `json:"error_message"`+ RetryCount int `json:"retry_count" gorm:"default:0;not null"`+ CreatedAt time.Time `json:"created_at"`+ SentAt *time.Time `json:"sent_at"`+ ScheduledAt *time.Time `json:"scheduled_at"`+ Provider string `json:"provider,omitempty" gorm:"index;size:32"`SMTPHostname string `json:"smtp_hostname,omitempty"`diff --git a/internal/models/suppression.go b/internal/models/suppression.goindex ac66974..9e19b40 100644--- a/internal/models/suppression.go+++ b/internal/models/suppression.go@@ -19,13 +19,30 @@ package modelsimport "time"+// SuppressionKind classifies why an address is suppressed. It makes the global+// vs list-scoped distinction explicit (rather than inferring it from list_id)+// and powers per-reason analytics and a future preference center.+type SuppressionKind string++const (+ SuppressionKindHard SuppressionKind = "hard" // manual/automated "block everything"+ SuppressionKindBounce SuppressionKind = "bounce" // hard bounce+ SuppressionKindComplaint SuppressionKind = "complaint" // spam/abuse complaint+ SuppressionKindListUnsubscribe SuppressionKind = "list_unsubscribe" // opted out of one list+ SuppressionKindManual SuppressionKind = "manual" // created via the management API+)+type Suppression struct {- ID uint `json:"id" gorm:"primaryKey"`- UserID uint `json:"user_id" gorm:"index;not null"`- WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`- Email string `json:"email" gorm:"not null"`- Reason string `json:"reason"`- CreatedAt time.Time `json:"created_at"`+ ID uint `json:"id" gorm:"primaryKey"`+ UserID uint `json:"user_id" gorm:"index;not null"`+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`+ Email string `json:"email" gorm:"not null"`+ // ListID nil = global block (bounces, complaints, manual, "unsubscribe from+ // everything"); set = opt-out of that UnsubscribeList only.+ ListID *uint `json:"list_id,omitempty" gorm:"index"`+ Kind SuppressionKind `json:"kind" gorm:"type:varchar(20);default:'hard';not null"`+ Reason string `json:"reason"`+ CreatedAt time.Time `json:"created_at"`User User `json:"-" gorm:"foreignKey:UserID"`}diff --git a/internal/models/unsubscribe_list.go b/internal/models/unsubscribe_list.gonew file mode 100644index 0000000..8a22732--- /dev/null+++ b/internal/models/unsubscribe_list.go@@ -0,0 +1,47 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package models++import "time"++// UnsubscribeList is a transactional opt-out scope. It is email-keyed (decoupled+// from Subscriber) and carries no membership: a recipient is never enrolled, the+// list is purely a suppression scope referenced by a send. A one-click on a link+// minted for an email that names a list writes a list-scoped Suppression, so the+// recipient's other transactional mail (receipts, password resets) keeps flowing.+//+// It is distinct from SubscriberList (campaign audiences, subscriber-keyed) and+// its SubscriberListUnsubscribe opt-out table.+type UnsubscribeList struct {+ ID uint `json:"id" gorm:"primaryKey"`+ // UUID is the opaque, non-enumerable public handle (for hosted pages / webhook+ // payloads). The authenticated API still references the list by id.+ UUID string `json:"uuid" gorm:"type:uuid;default:gen_random_uuid();uniqueIndex;not null"`+ UserID uint `json:"user_id" gorm:"index;not null"`+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`+ Name string `json:"name" gorm:"not null"` // unique per scope (internal label)+ // PublicName is shown to recipients on the unsubscribe/preference page. Falls+ // back to Name when empty.+ PublicName string `json:"public_name,omitempty"`+ Description string `json:"description"`+ Active bool `json:"active" gorm:"default:true;not null"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt *time.Time `json:"updated_at"`++ User User `json:"-" gorm:"foreignKey:UserID"`+}diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 35d8bfc..604cb8f 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -94,6 +94,7 @@ type routerHandlers struct {domain *handlers.DomainHandlerbounce *handlers.BounceHandlersuppression *handlers.SuppressionHandler+ unsubscribeList *handlers.UnsubscribeListHandlercontact *handlers.ContactHandleradmin *handlers.AdminHandlerworkspace *handlers.WorkspaceHandler@@ -130,6 +131,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cdomainRepo := repositories.NewDomainRepository(db)bounceRepo := repositories.NewBounceRepository(db)suppressionRepo := repositories.NewSuppressionRepository(db)+ unsubListRepo := repositories.NewUnsubscribeListRepository(db)stylesheetRepo := repositories.NewStyleSheetRepository(db)versionRepo := repositories.NewTemplateVersionRepository(db)localizationRepo := repositories.NewTemplateLocalizationRepository(db)@@ -170,6 +172,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cemailService.SetPlanLimits(&emailPlanAdapter{planService})emailService.SetVersionRepos(versionRepo, localizationRepo)emailService.SetContactRepo(contactRepo)+ emailService.SetUnsubscribeListRepo(unsubListRepo)emailService.SetDomainVerification(domainRepo, userRepo)if producer != nil {emailService.SetEnqueuer(producer)@@ -238,8 +241,9 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cwebhookDelivery: handlers.NewWebhookDeliveryHandler(webhookDeliveryRepo),dashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),domain: handlers.NewDomainHandler(domainRepo),- bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo),- suppression: handlers.NewSuppressionHandler(suppressionRepo),+ bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo, dispatcher),+ suppression: handlers.NewSuppressionHandler(suppressionRepo, unsubListRepo),+ unsubscribeList: handlers.NewUnsubscribeListHandler(unsubListRepo),contact: handlers.NewContactHandler(contactRepo, suppressionRepo),admin: handlers.NewAdminHandler(db, statsCache, userRepo, apiKeyRepo, emailRepo, webhookDeliveryRepo, inspector, bus, userSeeder, cfg.EmbeddedWorker),workspace: handlers.NewWorkspaceHandler(workspaceRepo, userRepo, db),@@ -323,7 +327,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c// TrackingtrackingRepo := repositories.NewTrackingRepository(db)trackingService := tracking.NewService(trackingRepo, cfg.AppWebURL, []byte(cfg.JWTSecret))- r.h.tracking = handlers.NewTrackingHandler(trackingRepo, campaignMessageRepo, campaignRepo, subscriberRepo, subscriberListRepo, emailRepo, suppressionRepo, trackingService)+ r.h.tracking = handlers.NewTrackingHandler(trackingRepo, campaignMessageRepo, campaignRepo, subscriberRepo, subscriberListRepo, emailRepo, suppressionRepo, trackingService, dispatcher)// Wire the generator for Posta-injected public links (one-click unsubscribe +// hosted "view in browser"), used to resolve reserved {{ posta_* }} templatediff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.goindex 44e9dc6..9cde2b7 100644--- a/internal/routes/user_routes.go+++ b/internal/routes/user_routes.go@@ -929,7 +929,7 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {Handler: okapi.H(r.h.suppression.List),Group: userGroup,Summary: "List suppressed emails",- Request: &handlers.ListRequest{},+ Request: &handlers.ListSuppressionsRequest{},Response: &dto.PageableResponse[models.Suppression]{},},{@@ -945,6 +945,61 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {},},+ // ==================== Unsubscribe Lists ====================+ {+ Method: http.MethodPost,+ Path: "/unsubscribe-lists",+ Handler: okapi.H(r.h.unsubscribeList.Create),+ Group: userGroup,+ Tags: []string{"Unsubscribe Lists"},+ Summary: "Create unsubscribe list",+ Request: &handlers.CreateUnsubscribeListRequest{},+ Options: []okapi.RouteOption{+ okapi.DocResponse(201, &dto.Response[models.UnsubscribeList]{}),+ okapi.DocErrorResponse(409, &dto.ErrorResponseBody{}),+ },+ },+ {+ Method: http.MethodGet,+ Path: "/unsubscribe-lists",+ Handler: okapi.H(r.h.unsubscribeList.List),+ Group: userGroup,+ Tags: []string{"Unsubscribe Lists"},+ Summary: "List unsubscribe lists",+ Request: &handlers.ListRequest{},+ Response: &dto.PageableResponse[models.UnsubscribeList]{},+ },+ {+ Method: http.MethodGet,+ Path: "/unsubscribe-lists/{id:int}",+ Handler: okapi.H(r.h.unsubscribeList.Get),+ Group: userGroup,+ Tags: []string{"Unsubscribe Lists"},+ Summary: "Get unsubscribe list",+ Response: &dto.Response[models.UnsubscribeList]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},+ },+ {+ Method: http.MethodPut,+ Path: "/unsubscribe-lists/{id:int}",+ Handler: okapi.H(r.h.unsubscribeList.Update),+ Group: userGroup,+ Tags: []string{"Unsubscribe Lists"},+ Summary: "Update unsubscribe list",+ Request: &handlers.UpdateUnsubscribeListRequest{},+ Response: &dto.Response[models.UnsubscribeList]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID")},+ },+ {+ Method: http.MethodDelete,+ Path: "/unsubscribe-lists/{id:int}",+ Handler: okapi.H(r.h.unsubscribeList.Delete),+ Group: userGroup,+ Tags: []string{"Unsubscribe Lists"},+ Summary: "Delete unsubscribe list",+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "List ID"), okapi.DocResponse(204, nil)},+ },+// ==================== Audit Log ===================={Method: http.MethodGet,diff --git a/internal/services/email/service.go b/internal/services/email/service.goindex 2a5e277..1242f5a 100644--- a/internal/services/email/service.go+++ b/internal/services/email/service.go@@ -22,6 +22,7 @@ import ("context""encoding/base64""encoding/json"+ "errors""fmt""io""net/mail"@@ -79,6 +80,7 @@ type Service struct {smtpRepo *repositories.SMTPRepositorytemplateRepo *repositories.TemplateRepositorysuppressionRepo *repositories.SuppressionRepository+ unsubRepo *repositories.UnsubscribeListRepositoryversionRepo *repositories.TemplateVersionRepositorylocalizationRepo *repositories.TemplateLocalizationRepositorycontactRepo *repositories.ContactRepository@@ -132,6 +134,12 @@ func (s *Service) SetContactRepo(cr *repositories.ContactRepository) {s.contactRepo = cr}+// SetUnsubscribeListRepo wires the repository used to validate Posta-managed+// unsubscribe-list references at send time.+func (s *Service) SetUnsubscribeListRepo(r *repositories.UnsubscribeListRepository) {+ s.unsubRepo = r+}+// SetDomainVerification sets the domain and user repositories for enforcing verified domain sending.func (s *Service) SetDomainVerification(dr *repositories.DomainRepository, ur *repositories.UserRepository) {s.domainRepo = dr@@ -232,21 +240,101 @@ func (s *Service) OnFailed(fn func()) { s.onFailed = fn }// OnQueued sets a callback invoked after each email is enqueued for delivery.func (s *Service) OnQueued(fn func()) { s.onQueued = fn }+var (+ ErrUnsubscribeListNotFound = errors.New("unsubscribe list not found in scope")+ ErrUnsubscribeInvalid = errors.New("invalid unsubscribe configuration")+)++// Unsubscribe configures the List-Unsubscribe headers (RFC 2369 / 8058) and, for+// the Posta-managed path, list-scoped suppression on a one-click opt-out.+type Unsubscribe struct {+ // ListID (Posta-managed): reference an existing UnsubscribeList by id. Posta+ // generates the signed one-click URL + List-Unsubscribe-Post, and a click+ // suppresses the recipient on that list only. Mutually exclusive with URL.+ ListID *uint `json:"list_id,omitempty"`++ // URL (caller-managed): you own the endpoint; Posta only emits the header.+ // Also the RFC 8058 POST target when OneClick is set.+ URL string `json:"url,omitempty"`+ // Mailto is an optional mailto: unsubscribe (RFC 2369), emitted alongside URL.+ Mailto string `json:"mailto,omitempty"`+ // OneClick emits "List-Unsubscribe-Post: List-Unsubscribe=One-Click" (requires+ // an https URL for the caller-managed path).+ OneClick bool `json:"one_click,omitempty"`+}+type SendRequest struct {- From string `json:"from" required:"true"`- To []string `json:"to" required:"true" minItems:"1"`- Subject string `json:"subject" required:"true"`- HTML string `json:"html"`- Text string `json:"text"`- Attachments []models.Attachment `json:"attachments,omitempty"`- Headers map[string]string `json:"headers,omitempty"`- ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty"`- ListUnsubscribePost bool `json:"list_unsubscribe_post,omitempty"`- SendAt *time.Time `json:"send_at,omitempty"`+ From string `json:"from" required:"true"`+ To []string `json:"to" required:"true" minItems:"1"`+ Subject string `json:"subject" required:"true"`+ HTML string `json:"html"`+ Text string `json:"text"`+ Attachments []models.Attachment `json:"attachments,omitempty"`+ Headers map[string]string `json:"headers,omitempty"`+ Unsubscribe *Unsubscribe `json:"unsubscribe,omitempty"`+ // Deprecated: use Unsubscribe. Kept for one minor release; mapped onto+ // Unsubscribe{URL, OneClick} in resolveUnsubscribe.+ ListUnsubscribeURL string `json:"list_unsubscribe_url,omitempty" deprecated:"true"`+ ListUnsubscribePost bool `json:"list_unsubscribe_post,omitempty" deprecated:"true"`+ SendAt *time.Time `json:"send_at,omitempty"`// TemplateName is populated by internal template-send pathsTemplateName string `json:"-"`}+// resolvedUnsub is the normalized, validated unsubscribe config used internally.+type resolvedUnsub struct {+ listID *uint // Posta-managed list (validated + owned)+ url string // caller-managed https URL+ mailto string // normalized mailto: URI+ oneClick bool // emit List-Unsubscribe-Post+}++// resolveUnsubscribe normalizes the request's unsubscribe config+func (s *Service) resolveUnsubscribe(scope repositories.ResourceScope, req *SendRequest) (*resolvedUnsub, error) {+ u := req.Unsubscribe+ // Map legacy fields onto the object when the new one is absent.+ if u == nil {+ if req.ListUnsubscribeURL == "" && !req.ListUnsubscribePost {+ return nil, nil+ }+ logger.Warn("list_unsubscribe_url/list_unsubscribe_post are deprecated; use the unsubscribe object")+ u = &Unsubscribe{URL: req.ListUnsubscribeURL, OneClick: req.ListUnsubscribePost}+ }++ if u.ListID != nil && u.URL != "" {+ return nil, fmt.Errorf("%w: list_id and url are mutually exclusive", ErrUnsubscribeInvalid)+ }++ mailto := strings.TrimSpace(u.Mailto)+ if mailto != "" && !strings.HasPrefix(strings.ToLower(mailto), "mailto:") {+ mailto = "mailto:" + mailto+ }++ // Posta-managed: validate + own the list. The one-click URL is minted later+ // (it needs the email id); OneClick is implied.+ if u.ListID != nil {+ if s.unsubRepo == nil {+ return nil, fmt.Errorf("%w: list-managed unsubscribe is not configured", ErrUnsubscribeInvalid)+ }+ if _, err := s.unsubRepo.FindByIDForScope(*u.ListID, scope); err != nil {+ return nil, fmt.Errorf("%w: list_id %d", ErrUnsubscribeListNotFound, *u.ListID)+ }+ return &resolvedUnsub{listID: u.ListID, mailto: mailto, oneClick: true}, nil+ }++ // Caller-managed.+ if u.URL == "" {+ if mailto == "" {+ return nil, nil+ }+ return &resolvedUnsub{mailto: mailto}, nil+ }+ if u.OneClick && !strings.HasPrefix(strings.ToLower(u.URL), "https://") {+ return nil, fmt.Errorf("%w: one_click requires an https url", ErrUnsubscribeInvalid)+ }+ return &resolvedUnsub{url: u.URL, mailto: mailto, oneClick: u.OneClick}, nil+}+type SendTemplateRequest struct {TemplateID *uint `json:"template_id,omitempty" doc:"Template ID (preferred, uses primary key index)"`Template string `json:"template" doc:"Template name (fallback when template_id is not provided)"`@@ -255,6 +343,7 @@ type SendTemplateRequest struct {To []string `json:"to" required:"true" minItems:"1"`TemplateData map[string]any `json:"template_data"`Attachments []models.Attachment `json:"attachments,omitempty"`+ Unsubscribe *Unsubscribe `json:"unsubscribe,omitempty"`}type SendResponse struct {@@ -268,6 +357,9 @@ type BatchRequest struct {Language string `json:"language"`From string `json:"from"`Recipients []BatchRecipient `json:"recipients" required:"true" minItems:"1"`+ // Unsubscribe applies to every recipient in the batch (same list / URL / mailto).+ // Per-recipient unsubscribe is intentionally not supported.+ Unsubscribe *Unsubscribe `json:"unsubscribe,omitempty"`}type BatchRecipient struct {@@ -339,10 +431,18 @@ func (s *Service) ValidateSend(ctx context.Context, userID uint, workspaceID *ui}scope := repositories.ResourceScope{UserID: userID, WorkspaceID: workspaceID}+ unsub, err := s.resolveUnsubscribe(scope, req)+ if err != nil {+ return nil, err+ }+ var unsubListID *uint+ if unsub != nil {+ unsubListID = unsub.listID+ }activeRecipients := req.TosuppressedCount := 0if s.suppressionRepo != nil {- filtered, err := s.suppressionRepo.FilterSuppressed(scope, req.To)+ filtered, err := s.suppressionRepo.FilterSuppressedForList(scope, req.To, unsubListID)if err != nil {return nil, fmt.Errorf("failed to check suppression list: %w", err)}@@ -387,6 +487,7 @@ func (s *Service) ValidateSendWithTemplate(ctx context.Context, userID uint, worHTML: rendered.HTML,Text: rendered.Text,Attachments: req.Attachments,+ Unsubscribe: req.Unsubscribe,})if err != nil {return nil, err@@ -431,10 +532,18 @@ func (s *Service) ValidateSendBatch(ctx context.Context, userID uint, workspaceI}scope := repositories.ResourceScope{UserID: userID, WorkspaceID: workspaceID}+ unsub, err := s.resolveUnsubscribe(scope, &SendRequest{Unsubscribe: req.Unsubscribe})+ if err != nil {+ return nil, err+ }+ var unsubListID *uint+ if unsub != nil {+ unsubListID = unsub.listID+ }activeRecipients := emailssuppressedCount := 0if s.suppressionRepo != nil {- filtered, err := s.suppressionRepo.FilterSuppressed(scope, emails)+ filtered, err := s.suppressionRepo.FilterSuppressedForList(scope, emails, unsubListID)if err != nil {return nil, fmt.Errorf("failed to check suppression list: %w", err)}@@ -499,10 +608,21 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *}}- // Filter out suppressed recipients+ // Resolve + validate the unsubscribe config (Posta-managed list, or caller-managed+ // url/mailto). nil ⇒ no headers, no suppression — the transactional default.scope := repositories.ResourceScope{UserID: userID, WorkspaceID: workspaceID}+ unsub, err := s.resolveUnsubscribe(scope, req)+ if err != nil {+ return nil, err+ }+ var unsubListID *uint+ if unsub != nil {+ unsubListID = unsub.listID+ }++ // Filter out suppressed recipients (list-scoped when a list is named)if s.suppressionRepo != nil {- filtered, err := s.suppressionRepo.FilterSuppressed(scope, req.To)+ filtered, err := s.suppressionRepo.FilterSuppressedForList(scope, req.To, unsubListID)if err != nil {return nil, fmt.Errorf("failed to check suppression list: %w", err)}@@ -562,7 +682,6 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *if len(req.Attachments) > 0 {if s.blobStore != nil {// Generate a temporary UUID for the blob key prefix.- // The real email UUID is assigned by the DB, so we use a timestamp-based key.tempKey := fmt.Sprintf("%d", time.Now().UnixNano())uploaded, err := s.uploadAttachments(ctx, tempKey, req.Attachments)if err != nil {@@ -604,46 +723,69 @@ func (s *Service) Send(ctx context.Context, userID, apiKeyID uint, workspaceID *apiKeyPtr = &apiKeyID}+ // Posta-managed (list) URL is minted in the post-Create block (it needs em.ID),+ // which also sets ListUnsubscribePost for that path.+ var luURL, luMailto string+ var luPost bool+ if unsub != nil {+ luMailto = unsub.mailto+ if unsub.url != "" {+ luURL = unsub.url+ luPost = unsub.oneClick+ }+ }+em := &models.Email{// Assign the UUID up front so reserved {{ posta_* }} links (which key the// web view off the UUID) can be built without depending on the DB reading// the gen_random_uuid() default back after insert.- UUID: uuid.NewString(),- UserID: userID,- WorkspaceID: workspaceID,- APIKeyID: apiKeyPtr,- Sender: req.From,- Recipients: req.To,- Subject: req.Subject,- TemplateName: req.TemplateName,- HTMLBody: req.HTML,- TextBody: req.Text,- AttachmentsJSON: attachmentsJSON,- HeadersJSON: headersJSON,- ListUnsubscribeURL: req.ListUnsubscribeURL,- ListUnsubscribePost: req.ListUnsubscribePost,- Status: models.EmailStatusPending,- Provider: ClassifyRecipients(req.To),+ UUID: uuid.NewString(),+ UserID: userID,+ WorkspaceID: workspaceID,+ APIKeyID: apiKeyPtr,+ Sender: req.From,+ Recipients: req.To,+ Subject: req.Subject,+ TemplateName: req.TemplateName,+ HTMLBody: req.HTML,+ TextBody: req.Text,+ AttachmentsJSON: attachmentsJSON,+ HeadersJSON: headersJSON,+ ListUnsubscribeURL: luURL,+ ListUnsubscribeMailto: luMailto,+ ListUnsubscribePost: luPost,+ UnsubscribeListID: unsubListID,+ Status: models.EmailStatusPending,+ Provider: ClassifyRecipients(req.To),}if err := s.emailRepo.Create(em); err != nil {return nil, fmt.Errorf("failed to store email: %w", err)}- // Resolve reserved {{ posta_* }} system links now that the email identity is- // known. Rendering left sentinels in the body; replace them with the real- // per-message URLs. Only touches the DB when the template actually used one.- if s.linkGen != nil && (HasSystemSentinels(em.HTMLBody) || HasSystemSentinels(em.TextBody) || HasSystemSentinels(em.Subject)) {+ // Resolve reserved {{ posta_* }} system links and/or mint the Posta-managed+ // one-click unsubscribe URL now that the email identity (id/UUID) is known.+ // Both need em.ID/UUID, so they happen post-Create. Only touches the DB when a+ // template used a sentinel or a list was named.+ needsLinks := HasSystemSentinels(em.HTMLBody) || HasSystemSentinels(em.TextBody) || HasSystemSentinels(em.Subject)+ if s.linkGen != nil && (needsLinks || em.UnsubscribeListID != nil) {webViewURL := s.linkGen.WebViewURL(em.UUID)unsubscribeURL := s.linkGen.TxUnsubscribeURL(em.ID)- em.HTMLBody = SubstituteSystemLinks(em.HTMLBody, webViewURL, unsubscribeURL)- em.TextBody = SubstituteSystemLinks(em.TextBody, webViewURL, unsubscribeURL)- em.Subject = SubstituteSystemLinks(em.Subject, webViewURL, unsubscribeURL)- // Keep req in sync so the synchronous fallback (sendSync) sends the- // resolved body/subject too.- req.HTML = em.HTMLBody- req.Text = em.TextBody- req.Subject = em.Subject+ if needsLinks {+ em.HTMLBody = SubstituteSystemLinks(em.HTMLBody, webViewURL, unsubscribeURL)+ em.TextBody = SubstituteSystemLinks(em.TextBody, webViewURL, unsubscribeURL)+ em.Subject = SubstituteSystemLinks(em.Subject, webViewURL, unsubscribeURL)+ // Keep req in sync so the synchronous fallback (sendSync) sends the+ // resolved body/subject too.+ req.HTML = em.HTMLBody+ req.Text = em.TextBody+ req.Subject = em.Subject+ }+ // Posta-managed list: emit the RFC 8058 one-click List-Unsubscribe header.+ if em.UnsubscribeListID != nil {+ em.ListUnsubscribeURL = unsubscribeURL+ em.ListUnsubscribePost = true+ }_ = s.emailRepo.Update(em)}@@ -741,7 +883,7 @@ func (s *Service) sendSync(em *models.Email, userID uint, workspaceID *uint, reqem.SMTPHostname = smtpServer.Host_ = s.emailRepo.Update(em)- if err := s.sender.Send(smtpServer, req.From, req.To, req.Subject, req.HTML, req.Text, req.Attachments, req.Headers, req.ListUnsubscribeURL, req.ListUnsubscribePost); err != nil {+ if err := s.sender.Send(smtpServer, req.From, req.To, req.Subject, req.HTML, req.Text, req.Attachments, req.Headers, em.ListUnsubscribeURL, em.ListUnsubscribeMailto, em.ListUnsubscribePost); err != nil {em.Status = models.EmailStatusFailedem.ErrorMessage = err.Error()_ = s.emailRepo.Update(em)@@ -794,6 +936,7 @@ func (s *Service) SendWithTemplate(ctx context.Context, userID, apiKeyID uint, wText: rendered.Text,Attachments: req.Attachments,TemplateName: tmpl.Name,+ Unsubscribe: req.Unsubscribe,})}@@ -829,15 +972,27 @@ func (s *Service) SendBatch(ctx context.Context, userID, apiKeyID uint, workspacreturn nil, fmt.Errorf("template not found: %w", err)}+ // Resolve + validate the batch's unsubscribe config once upfront so a bad+ // list_id fails the batch immediately instead of replicating the error per row.+ scope := repositories.ResourceScope{UserID: userID, WorkspaceID: workspaceID}+ unsub, err := s.resolveUnsubscribe(scope, &SendRequest{Unsubscribe: req.Unsubscribe})+ if err != nil {+ return nil, err+ }+ var unsubListID *uint+ if unsub != nil {+ unsubListID = unsub.listID+ }+resp := &BatchResponse{Total: len(req.Recipients),Results: make([]BatchResult, 0, len(req.Recipients)),}for _, recipient := range req.Recipients {- // Check suppression+ // Check suppression (list-scoped when a list is named)if s.suppressionRepo != nil {- suppressed, err := s.suppressionRepo.IsSuppressed(repositories.ResourceScope{UserID: userID, WorkspaceID: workspaceID}, recipient.Email)+ suppressed, err := s.suppressionRepo.IsSuppressedForList(scope, recipient.Email, unsubListID)if err == nil && suppressed {// Log the suppressed emailvar apiKeyPtr *uint@@ -893,6 +1048,7 @@ func (s *Service) SendBatch(ctx context.Context, userID, apiKeyID uint, workspacHTML: rendered.HTML,Text: rendered.Text,TemplateName: tmpl.Name,+ Unsubscribe: req.Unsubscribe,})if err != nil {resp.Failed++diff --git a/internal/services/email/smtp_sender.go b/internal/services/email/smtp_sender.goindex b97d2df..8623c9c 100644--- a/internal/services/email/smtp_sender.go+++ b/internal/services/email/smtp_sender.go@@ -112,7 +112,7 @@ func (s *SMTPSender) TestConnection(server *models.SMTPServer) error {return client.Quit()}-func (s *SMTPSender) Send(server *models.SMTPServer, from string, to []string, subject, htmlBody, textBody string, attachments []models.Attachment, headers map[string]string, listUnsubscribeURL string, listUnsubscribePost bool) error {+func (s *SMTPSender) Send(server *models.SMTPServer, from string, to []string, subject, htmlBody, textBody string, attachments []models.Attachment, headers map[string]string, listUnsubscribeURL, listUnsubscribeMailto string, listUnsubscribePost bool) error {addr := fmt.Sprintf("%s:%d", server.Host, server.Port)var auth smtp.Auth@@ -120,7 +120,7 @@ func (s *SMTPSender) Send(server *models.SMTPServer, from string, to []string, sauth = smtp.PlainAuth("", server.Username, server.Password, server.Host)}- msg := buildMessage(from, to, subject, htmlBody, textBody, attachments, headers, listUnsubscribeURL, listUnsubscribePost)+ msg := buildMessage(from, to, subject, htmlBody, textBody, attachments, headers, listUnsubscribeURL, listUnsubscribeMailto, listUnsubscribePost)// Extract bare email for SMTP envelope (MAIL FROM), keep full format for headersenvelopeFrom := envelopeAddress(from)@@ -226,7 +226,7 @@ func wrapSendError(stage, recipient string, err error) error {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 {+func buildMessage(from string, to []string, subject, htmlBody, textBody string, attachments []models.Attachment, headers map[string]string, listUnsubscribeURL, listUnsubscribeMailto string, listUnsubscribePost bool) []byte {var b strings.Builderfmt.Fprintf(&b, "From: %s\r\n", from)@@ -234,10 +234,18 @@ func buildMessage(from string, to []string, subject, htmlBody, textBody string,fmt.Fprintf(&b, "Subject: %s\r\n", mime.QEncoding.Encode("UTF-8", subject))b.WriteString("MIME-Version: 1.0\r\n")- // RFC 8058: List-Unsubscribe headers+ // RFC 2369 / 8058 List-Unsubscribe. Emit mailto first, then the https URL.+ var luParts []string+ if listUnsubscribeMailto != "" {+ luParts = append(luParts, "<"+listUnsubscribeMailto+">")+ }if listUnsubscribeURL != "" {- fmt.Fprintf(&b, "List-Unsubscribe: <%s>\r\n", listUnsubscribeURL)- if listUnsubscribePost {+ luParts = append(luParts, "<"+listUnsubscribeURL+">")+ }+ if len(luParts) > 0 {+ fmt.Fprintf(&b, "List-Unsubscribe: %s\r\n", strings.Join(luParts, ", "))+ // RFC 8058 one-click applies to the https POST target only.+ if listUnsubscribePost && listUnsubscribeURL != "" {b.WriteString("List-Unsubscribe-Post: List-Unsubscribe=One-Click\r\n")}}diff --git a/internal/services/notification/service.go b/internal/services/notification/service.goindex 85bcddf..86fba14 100644--- a/internal/services/notification/service.go+++ b/internal/services/notification/service.go@@ -123,7 +123,7 @@ func (s *Service) Send(to, subject, templateName string, data map[string]any) er}server := s.systemServer()- if err := s.sender.Send(server, s.smtpCfg.From, []string{to}, subject, html, "", nil, nil, "", false); err != nil {+ if err := s.sender.Send(server, s.smtpCfg.From, []string{to}, subject, html, "", nil, nil, "", "", false); err != nil {return fmt.Errorf("notification send to %s: %w", to, err)}diff --git a/internal/services/retry/worker.go b/internal/services/retry/worker.goindex b0563b8..a5512c7 100644--- a/internal/services/retry/worker.go+++ b/internal/services/retry/worker.go@@ -155,7 +155,7 @@ func (w *Worker) retryEmail(em *models.Email, server *models.SMTPServer) {// Synchronous fallbackem.RetryCount++- if err := w.sender.Send(server, em.Sender, em.Recipients, em.Subject, em.HTMLBody, em.TextBody, nil, nil, em.ListUnsubscribeURL, em.ListUnsubscribePost); err != nil {+ if err := w.sender.Send(server, em.Sender, em.Recipients, em.Subject, em.HTMLBody, em.TextBody, nil, nil, em.ListUnsubscribeURL, em.ListUnsubscribeMailto, em.ListUnsubscribePost); err != nil {em.ErrorMessage = err.Error()_ = w.emailRepo.Update(em)logger.Debug("retry worker: email retry failed", "id", em.ID, "attempt", em.RetryCount, "error", err)diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.goindex 90fcf56..f2f2b76 100644--- a/internal/storage/migration/constraints.go+++ b/internal/storage/migration/constraints.go@@ -76,7 +76,9 @@ func rebuildUniqueIndexes(db *gorm.DB) {{"contacts", "idx_user_email", "email"},{"domains", "idx_user_domain", "domain"},{"languages", "idx_user_language", "code"},- {"suppressions", "idx_user_suppression", "email"},++ {"suppressions", "idx_user_suppression", "email, COALESCE(list_id, 0)"},+ {"unsubscribe_lists", "idx_user_unsub_list", "name"},}for _, idx := range indexes {diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.goindex 7480ba2..d8adb16 100644--- a/internal/storage/migration/migration.go+++ b/internal/storage/migration/migration.go@@ -50,6 +50,7 @@ func Run(db *gorm.DB) error {&models.Domain{},&models.Bounce{},&models.Suppression{},+ &models.UnsubscribeList{},&models.Contact{},&models.Event{},&models.Setting{},diff --git a/internal/storage/repositories/suppression_repo.go b/internal/storage/repositories/suppression_repo.goindex 9fe5c65..45c2626 100644--- a/internal/storage/repositories/suppression_repo.go+++ b/internal/storage/repositories/suppression_repo.go@@ -57,8 +57,26 @@ func (r *SuppressionRepository) Upsert(suppression *models.Suppression) error {return r.db.Clauses(clause.OnConflict{DoNothing: true}).Create(suppression).Error}-func (r *SuppressionRepository) Delete(scope ResourceScope, email string) error {- return ApplyScope(r.db, scope).Where("email = ?", normalizeEmail(email)).Delete(&models.Suppression{}).Error+// Delete removes a suppression for an email within scope.+func (r *SuppressionRepository) Delete(scope ResourceScope, email string, listID *uint) error {+ q := ApplyScope(r.db, scope).Where("email = ?", normalizeEmail(email))+ if listID != nil {+ q = q.Where("list_id = ?", *listID)+ } else {+ q = q.Where("list_id IS NULL")+ }+ return q.Delete(&models.Suppression{}).Error+}++// applyListPredicate scopes a suppression query to what blocks a send for the+// given list. listID nil ⇒ only global rows apply (list_id IS NULL). A set listID+// ⇒ a global block OR that list's opt-out applies (a global block always wins).+func applyListPredicate(db *gorm.DB, listID *uint) *gorm.DB {+ if listID != nil {+ // Explicit parens so the OR can't bind loosely against the scope/email ANDs.+ return db.Where("(list_id IS NULL OR list_id = ?)", *listID)+ }+ return db.Where("list_id IS NULL")}func (r *SuppressionRepository) FindByUserID(userID uint, limit, offset int) ([]models.Suppression, int64, error) {@@ -106,15 +124,46 @@ func (r *SuppressionRepository) FindByScope(scope ResourceScope, limit, offset ireturn items, total, nil}+// IsSuppressed reports whether email is suppressed at the global scope (no list).+func (r *SuppressionRepository) FindByScopeFiltered(scope ResourceScope, listID *uint, limit, offset int) ([]models.Suppression, int64, error) {+ var items []models.Suppression+ var total int64++ base := ApplyScope(r.db.Model(&models.Suppression{}), scope)+ if listID != nil {+ base = base.Where("list_id = ?", *listID)+ }+ base.Count(&total)++ q := ApplyScope(r.db, scope)+ if listID != nil {+ q = q.Where("list_id = ?", *listID)+ }+ if err := q.Order("created_at DESC").Limit(limit).Offset(offset).Find(&items).Error; err != nil {+ return nil, 0, err+ }+ return items, total, nil+}+func (r *SuppressionRepository) IsSuppressed(scope ResourceScope, email string) (bool, error) {+ return r.IsSuppressedForList(scope, email, nil)+}++func (r *SuppressionRepository) IsSuppressedForList(scope ResourceScope, email string, listID *uint) (bool, error) {var count int64- err := ApplyScope(r.db.Model(&models.Suppression{}), scope).+ err := applyListPredicate(ApplyScope(r.db.Model(&models.Suppression{}), scope), listID).Where("email = ?", normalizeEmail(email)).Count(&count).Errorreturn count > 0, err}func (r *SuppressionRepository) FilterSuppressed(scope ResourceScope, emails []string) ([]string, error) {+ return r.FilterSuppressedForList(scope, emails, nil)+}++// FilterSuppressedForList drops recipients blocked for the given list (global+// block, or that list's opt-out when listID is set).+func (r *SuppressionRepository) FilterSuppressedForList(scope ResourceScope, emails []string, listID *uint) ([]string, error) {if len(emails) == 0 {return emails, nil}@@ -125,7 +174,7 @@ func (r *SuppressionRepository) FilterSuppressed(scope ResourceScope, emails []s}var suppressed []string- if err := ApplyScope(r.db.Model(&models.Suppression{}), scope).+ if err := applyListPredicate(ApplyScope(r.db.Model(&models.Suppression{}), scope), listID).Where("email IN ?", lowered).Pluck("email", &suppressed).Error; err != nil {return nil, errdiff --git a/internal/storage/repositories/unsubscribe_list_repo.go b/internal/storage/repositories/unsubscribe_list_repo.gonew file mode 100644index 0000000..89e855f--- /dev/null+++ b/internal/storage/repositories/unsubscribe_list_repo.go@@ -0,0 +1,76 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package repositories++import (+ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+)++type UnsubscribeListRepository struct {+ db *gorm.DB+}++func NewUnsubscribeListRepository(db *gorm.DB) *UnsubscribeListRepository {+ return &UnsubscribeListRepository{db: db}+}++func (r *UnsubscribeListRepository) Create(list *models.UnsubscribeList) error {+ return r.db.Create(list).Error+}++func (r *UnsubscribeListRepository) FindByID(id uint) (*models.UnsubscribeList, error) {+ var list models.UnsubscribeList+ if err := r.db.First(&list, id).Error; err != nil {+ return nil, err+ }+ return &list, nil+}++// FindByIDForScope returns the list only if it belongs to the given scope.+// Used at send time to validate + own a referenced list in one place.+func (r *UnsubscribeListRepository) FindByIDForScope(id uint, scope ResourceScope) (*models.UnsubscribeList, error) {+ var list models.UnsubscribeList+ if err := ApplyScope(r.db, scope).First(&list, id).Error; err != nil {+ return nil, err+ }+ return &list, nil+}++func (r *UnsubscribeListRepository) FindByScope(scope ResourceScope, limit, offset int) ([]models.UnsubscribeList, int64, error) {+ var items []models.UnsubscribeList+ var total int64++ ApplyScope(r.db.Model(&models.UnsubscribeList{}), scope).Count(&total)++ if err := ApplyScope(r.db, scope).+ Order("created_at DESC").+ Limit(limit).Offset(offset).+ Find(&items).Error; err != nil {+ return nil, 0, err+ }+ return items, total, nil+}++func (r *UnsubscribeListRepository) Update(list *models.UnsubscribeList) error {+ return r.db.Save(list).Error+}++func (r *UnsubscribeListRepository) Delete(id uint) error {+ return r.db.Delete(&models.UnsubscribeList{}, id).Error+}diff --git a/internal/storage/repositories/user_repo.go b/internal/storage/repositories/user_repo.goindex 591877d..06075b8 100644--- a/internal/storage/repositories/user_repo.go+++ b/internal/storage/repositories/user_repo.go@@ -145,6 +145,12 @@ func (r *UserRepository) DeleteAllUserData(userID uint) error {if err := tx.Exec("DELETE FROM contact_lists WHERE user_id = ?", userID).Error; err != nil {return err}++ // Delete webhook_deliveries that reference the user's webhooks+ if err := tx.Exec("DELETE FROM webhook_deliveries WHERE webhook_id IN (SELECT id FROM webhooks WHERE user_id = ?)", userID).Error; err != nil {+ return err+ }+for _, table := range tables {if err := tx.Exec("DELETE FROM "+table+" WHERE user_id = ?", userID).Error; err != nil {return errdiff --git a/internal/worker/handler.go b/internal/worker/handler.goindex 7086293..260ad41 100644--- a/internal/worker/handler.go+++ b/internal/worker/handler.go@@ -270,7 +270,7 @@ func (h *EmailSendHandler) ProcessTask(ctx context.Context, t *asynq.Task) errorrecipients := []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 filtered, fErr := h.suppressionRepo.FilterSuppressedForList(scope, recipients, em.UnsubscribeListID); fErr == nil {if len(filtered) == 0 {em.Status = models.EmailStatusSuppressedem.ErrorMessage = "all recipients are suppressed"@@ -310,7 +310,7 @@ func (h *EmailSendHandler) ProcessTask(ctx context.Context, t *asynq.Task) errorh.stamper.Sign(headers, em, recipients, em.Subject)}- if err := h.sender.Send(smtpServer, em.Sender, 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.ListUnsubscribeMailto, 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)diff --git a/web/src/api/bounces.ts b/web/src/api/bounces.tsindex 6f16279..220b362 100644--- a/web/src/api/bounces.ts+++ b/web/src/api/bounces.ts@@ -11,13 +11,17 @@ export const bouncesApi = {}export const suppressionsApi = {- list(page = 0, size = 20) {- return api.get<PaginatedResponse<Suppression>>('/users/me/suppressions', { params: { page, size } })+ list(page = 0, size = 20, listId?: number) {+ const params: Record<string, number> = { page, size }+ if (listId) params.list_id = listId+ return api.get<PaginatedResponse<Suppression>>('/users/me/suppressions', { params })},- create(data: { email: string; reason: string }) {+ create(data: { email: string; reason: string; list_id?: number }) {return api.post<ApiResponse<Suppression>>('/users/me/suppressions', data)},- delete(email: string) {- return api.delete('/users/me/suppressions', { data: { email } })+ delete(email: string, listId?: number) {+ const body: Record<string, string | number> = { email }+ if (listId) body.list_id = listId+ return api.delete('/users/me/suppressions', { data: body })},}diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 8baf25e..2af736e 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -254,6 +254,26 @@ export interface LanguageInput {is_default?: boolean}+export interface UnsubscribeListItem {+ id: number+ uuid: string+ user_id: number+ workspace_id?: number | null+ name: string+ public_name?: string+ description?: string+ active: boolean+ created_at: string+ updated_at?: string | null+}++export interface UnsubscribeListInput {+ name: string+ public_name?: string+ description?: string+ active?: boolean+}+export interface StyleSheet {id: numberuser_id: number@@ -385,6 +405,8 @@ export interface Suppression {id: numberuser_id: numberemail: string+ list_id?: number | null+ kind?: stringreason: stringcreated_at: string}diff --git a/web/src/api/unsubscribeLists.ts b/web/src/api/unsubscribeLists.tsnew file mode 100644index 0000000..b47c644--- /dev/null+++ b/web/src/api/unsubscribeLists.ts@@ -0,0 +1,20 @@+import api from './client'+import type { ApiResponse, PaginatedResponse, UnsubscribeListItem, UnsubscribeListInput } from './types'++export const unsubscribeListsApi = {+ list(page = 0, size = 20) {+ return api.get<PaginatedResponse<UnsubscribeListItem>>('/users/me/unsubscribe-lists', { params: { page, size } })+ },+ get(id: number) {+ return api.get<ApiResponse<UnsubscribeListItem>>(`/users/me/unsubscribe-lists/${id}`)+ },+ create(data: UnsubscribeListInput) {+ return api.post<ApiResponse<UnsubscribeListItem>>('/users/me/unsubscribe-lists', data)+ },+ update(id: number, data: Partial<UnsubscribeListInput>) {+ return api.put<ApiResponse<UnsubscribeListItem>>(`/users/me/unsubscribe-lists/${id}`, data)+ },+ delete(id: number) {+ return api.delete(`/users/me/unsubscribe-lists/${id}`)+ },+}diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex 75e3b7a..b1cd7e5 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -61,8 +61,9 @@ const navItems = [{ name: 'Deliveries', path: '/webhook-deliveries', icon: 'activity' },{ name: 'Contacts', path: '/contacts', icon: 'users' },{ name: 'Subscribers', path: '/subscribers', icon: 'users' },- { name: 'Lists', path: '/subscriber-lists', icon: 'list' },+ { name: 'Subscriber Lists', path: '/subscriber-lists', icon: 'list' },{ name: 'Campaigns', path: '/campaigns', icon: 'send' },+ { name: 'Unsubscribe Lists', path: '/unsubscribe-lists', icon: 'mail-x' },{ name: 'Bounces', path: '/bounces', icon: 'alert-triangle' },{ name: 'API Keys', path: '/api-keys', icon: 'key' },{ name: 'Audit Log', path: '/audit-log', icon: 'activity' },@@ -128,6 +129,7 @@ function getIcon(name: string): string {'settings': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="2.25" stroke="currentColor" stroke-width="1.5"/><path d="M14.7 11.1a1.2 1.2 0 00.24 1.32l.04.04a1.46 1.46 0 11-2.06 2.06l-.04-.04a1.2 1.2 0 00-1.32-.24 1.2 1.2 0 00-.73 1.1v.12a1.46 1.46 0 01-2.91 0v-.06a1.2 1.2 0 00-.79-1.1 1.2 1.2 0 00-1.32.24l-.04.04a1.46 1.46 0 11-2.06-2.06l.04-.04a1.2 1.2 0 00.24-1.32 1.2 1.2 0 00-1.1-.73h-.12a1.46 1.46 0 010-2.91h.06a1.2 1.2 0 001.1-.79 1.2 1.2 0 00-.24-1.32l-.04-.04a1.46 1.46 0 112.06-2.06l.04.04a1.2 1.2 0 001.32.24h.06a1.2 1.2 0 00.73-1.1v-.12a1.46 1.46 0 012.91 0v.06a1.2 1.2 0 00.73 1.1 1.2 1.2 0 001.32-.24l.04-.04a1.46 1.46 0 112.06 2.06l-.04.04a1.2 1.2 0 00-.24 1.32v.06a1.2 1.2 0 001.1.73h.12a1.46 1.46 0 010 2.91h-.06a1.2 1.2 0 00-1.1.73z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>','layers': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M9 1.5L1.5 6 9 10.5 16.5 6 9 1.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M1.5 12L9 16.5 16.5 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M1.5 9L9 13.5 16.5 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>','info': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.5"/><path d="M9 12.75V9M9 5.25h.007" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',+ 'mail-x': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M16 8.5V4a2 2 0 00-2-2H4a2 2 0 00-2 2v8a2 2 0 002 2h6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M2 4.5l7 5 7-5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M12.5 12.5l3.5 3.5M16 12.5l-3.5 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',}return icons[name] || ''}diff --git a/web/src/router/index.ts b/web/src/router/index.tsindex c40eab1..28a14ec 100644--- a/web/src/router/index.ts+++ b/web/src/router/index.ts@@ -66,6 +66,8 @@ const routes = [{ path: 'subscribers/:id', name: 'subscriber-detail', component: () => import('../views/subscribers/SubscriberDetail.vue'), meta: { title: 'Subscriber' } },{ path: 'subscriber-lists', name: 'subscriber-lists-page', component: () => import('../views/subscriber-lists/SubscriberLists.vue'), meta: { title: 'Subscriber Lists' } },{ path: 'subscriber-lists/:id', name: 'subscriber-list-detail', component: () => import('../views/subscriber-lists/SubscriberListDetail.vue'), meta: { title: 'Subscriber List' } },+ { path: 'unsubscribe-lists', name: 'unsubscribe-lists-page', component: () => import('../views/unsubscribe-lists/UnsubscribeLists.vue'), meta: { title: 'Unsubscribe Lists' } },+ { path: 'unsubscribe-lists/:id', name: 'unsubscribe-list-detail', component: () => import('../views/unsubscribe-lists/UnsubscribeListDetail.vue'), meta: { title: 'Unsubscribe List' } },{ path: 'campaigns', name: 'campaigns', component: () => import('../views/campaigns/Campaigns.vue'), meta: { title: 'Campaigns' } },{ path: 'campaigns/:id', name: 'campaign-detail', component: () => import('../views/campaigns/CampaignDetail.vue'), meta: { title: 'Campaign' } },{ path: 'analytics', name: 'analytics', component: () => import('../views/analytics/Analytics.vue'), meta: { title: 'Analytics' } },diff --git a/web/src/views/subscriber-lists/SubscriberLists.vue b/web/src/views/subscriber-lists/SubscriberLists.vueindex 04a948b..44e516f 100644--- a/web/src/views/subscriber-lists/SubscriberLists.vue+++ b/web/src/views/subscriber-lists/SubscriberLists.vue@@ -120,7 +120,7 @@ const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {<template><div><div class="page-header">- <h1>Lists</h1>+ <h1>Subscriber Lists</h1><button v-if="wsStore.canEdit" class="btn btn-primary" @click="openCreate">Create List</button></div>diff --git a/web/src/views/templates/TemplateEditor.vue b/web/src/views/templates/TemplateEditor.vueindex 1844623..47811ca 100644--- a/web/src/views/templates/TemplateEditor.vue+++ b/web/src/views/templates/TemplateEditor.vue@@ -392,7 +392,7 @@ function switchToVisualBuilder() {<!-- Preview content --><div class="preview-content">- <div v-if="previewTab === 'html'">+ <div v-if="previewTab === 'html'" class="preview-html"><iframev-if="preview?.html":srcdoc="preview.html"@@ -600,7 +600,12 @@ function switchToVisualBuilder() {overflow: auto;}+.preview-html {+ height: 100%;+}+.preview-iframe {+ display: block;width: 100%;height: 100%;min-height: 400px;diff --git a/web/src/views/unsubscribe-lists/UnsubscribeListDetail.vue b/web/src/views/unsubscribe-lists/UnsubscribeListDetail.vuenew file mode 100644index 0000000..949e3b9--- /dev/null+++ b/web/src/views/unsubscribe-lists/UnsubscribeListDetail.vue@@ -0,0 +1,153 @@+<script setup lang="ts">+import { ref, onMounted } from 'vue'+import { useRoute, useRouter } from 'vue-router'+import { unsubscribeListsApi } from '../../api/unsubscribeLists'+import { suppressionsApi } from '../../api/bounces'+import type { UnsubscribeListItem, Suppression, Pageable } from '../../api/types'+import { useNotificationStore } from '../../stores/notification'+import { useConfirm } from '../../composables/useConfirm'+import { useWorkspaceStore } from '../../stores/workspace'+import Pagination from '@/components/Pagination.vue'++const route = useRoute()+const router = useRouter()+const notify = useNotificationStore()+const wsStore = useWorkspaceStore()+const { confirm } = useConfirm()++const listId = Number(route.params.id)+const list = ref<UnsubscribeListItem | null>(null)+const optouts = ref<Suppression[]>([])+const pageable = ref<Pageable>({ current_page: 0, size: 20, total_pages: 0, total_elements: 0, empty: true })+const loading = ref(true)++async function loadList() {+ try {+ const res = await unsubscribeListsApi.get(listId)+ list.value = res.data.data+ } catch {+ notify.error('Unsubscribe list not found')+ router.push({ name: 'unsubscribe-lists-page' })+ }+}++async function loadOptouts(page = 0) {+ loading.value = true+ try {+ const res = await suppressionsApi.list(page, pageable.value.size, listId)+ optouts.value = res.data.data ?? []+ pageable.value = res.data.pageable+ } catch {+ notify.error('Failed to load opt-outs')+ } finally {+ loading.value = false+ }+}++async function removeOptout(s: Suppression) {+ const confirmed = await confirm({+ title: 'Remove opt-out',+ message: `Resubscribe ${s.email} to this list? Mail scoped to this list will reach them again.`,+ confirmText: 'Remove',+ variant: 'danger',+ })+ if (!confirmed) return+ try {+ await suppressionsApi.delete(s.email, listId)+ notify.success('Opt-out removed')+ await loadOptouts(pageable.value.current_page)+ } catch {+ notify.error('Failed to remove opt-out')+ }+}++function formatDate(dateStr: string): string {+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })+}++onMounted(async () => {+ await loadList()+ await loadOptouts(0)+})+</script>++<template>+ <div>+ <div class="page-header">+ <div>+ <a class="link" @click="router.push({ name: 'unsubscribe-lists-page' })">← Unsubscribe Lists</a>+ <h1 v-if="list">{{ list.name }}</h1>+ </div>+ </div>++ <div v-if="loading && !list" class="loading-page">+ <div class="spinner"></div>+ </div>++ <template v-else-if="list">+ <div class="card" style="margin-bottom: 16px;">+ <div style="display: flex; flex-wrap: wrap; gap: 32px;">+ <div>+ <div class="form-hint">Opt-outs</div>+ <div style="font-size: 22px; font-weight: 600;">{{ pageable.total_elements }}</div>+ </div>+ <div>+ <div class="form-hint">Public name</div>+ <div>{{ list.public_name || list.name }}</div>+ </div>+ <div>+ <div class="form-hint">Status</div>+ <div>+ <span :class="list.active ? 'badge badge-success' : 'badge badge-neutral'">+ {{ list.active ? 'Active' : 'Archived' }}+ </span>+ </div>+ </div>+ <div>+ <div class="form-hint">List ID</div>+ <div>{{ list.id }}</div>+ </div>+ </div>+ <p v-if="list.description" style="margin-top: 16px; color: var(--text-secondary, #6b7280);">{{ list.description }}</p>+ </div>++ <div class="card">+ <div class="card-header">+ <h3>Opted-out recipients</h3>+ </div>++ <div v-if="optouts.length === 0" class="empty-state">+ <h3>No opt-outs yet</h3>+ <p>Recipients who click the one-click unsubscribe on a send that references this list appear here.</p>+ </div>++ <template v-else>+ <div class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th>Email</th>+ <th>Reason</th>+ <th>Date</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="s in optouts" :key="s.id">+ <td>{{ s.email }}</td>+ <td>{{ s.reason || '—' }}</td>+ <td>{{ formatDate(s.created_at) }}</td>+ <td>+ <button v-if="wsStore.canEdit" class="btn btn-secondary btn-sm" @click="removeOptout(s)">Remove</button>+ </td>+ </tr>+ </tbody>+ </table>+ </div>++ <Pagination :pageable="pageable" @page="loadOptouts" />+ </template>+ </div>+ </template>+ </div>+</template>diff --git a/web/src/views/unsubscribe-lists/UnsubscribeLists.vue b/web/src/views/unsubscribe-lists/UnsubscribeLists.vuenew file mode 100644index 0000000..8be5dee--- /dev/null+++ b/web/src/views/unsubscribe-lists/UnsubscribeLists.vue@@ -0,0 +1,262 @@+<script setup lang="ts">+import { ref } from 'vue'+import { useRouter } from 'vue-router'+import { unsubscribeListsApi } from '../../api/unsubscribeLists'+import type { UnsubscribeListItem, UnsubscribeListInput } from '../../api/types'+import { useNotificationStore } from '../../stores/notification'+import { useConfirm } from '../../composables/useConfirm'+import { useModalSafeClose } from '../../composables/useModalSafeClose'+import { useWorkspaceStore } from '../../stores/workspace'+import { usePagination } from '@/composables/usePagination'+import Pagination from '@/components/Pagination.vue'++const router = useRouter()+const notify = useNotificationStore()+const wsStore = useWorkspaceStore()+const { confirm } = useConfirm()++const lists = ref<UnsubscribeListItem[]>([])+const loading = ref(true)+const showInfo = ref(false)++async function copyListId(id: number) {+ try {+ await navigator.clipboard.writeText(String(id))+ notify.success(`List ID ${id} copied`)+ } catch {+ notify.error('Failed to copy')+ }+}++const showModal = ref(false)+const editing = ref<UnsubscribeListItem | null>(null)+const saving = ref(false)++const form = ref<UnsubscribeListInput>({+ name: '',+ public_name: '',+ description: '',+ active: true,+})++function resetForm() {+ form.value = { name: '', public_name: '', description: '', active: true }+ editing.value = null+}++function openCreate() {+ resetForm()+ showModal.value = true+}++function openEdit(list: UnsubscribeListItem) {+ editing.value = list+ form.value = {+ name: list.name,+ public_name: list.public_name || '',+ description: list.description || '',+ active: list.active,+ }+ showModal.value = true+}++function closeModal() {+ showModal.value = false+ resetForm()+}++const { pageable, goToPage } = usePagination(async (page) => {+ loading.value = true+ try {+ const res = await unsubscribeListsApi.list(page, pageable.value.size)+ lists.value = res.data.data+ pageable.value = res.data.pageable+ } catch (e) {+ console.error('Failed to load unsubscribe lists', e)+ } finally {+ loading.value = false+ }+})++async function saveList() {+ if (!form.value.name.trim()) return+ saving.value = true+ try {+ if (editing.value) {+ await unsubscribeListsApi.update(editing.value.id, form.value)+ notify.success('Unsubscribe list updated')+ } else {+ await unsubscribeListsApi.create(form.value)+ notify.success('Unsubscribe list created')+ }+ closeModal()+ await goToPage(pageable.value.current_page)+ } catch {+ notify.error(editing.value ? 'Failed to update unsubscribe list' : 'A list with that name already exists')+ } finally {+ saving.value = false+ }+}++async function deleteList(list: UnsubscribeListItem) {+ const confirmed = await confirm({+ title: 'Delete Unsubscribe List',+ message: `Delete "${list.name}"? Existing per-list opt-outs that reference it will remain on the suppression list.`,+ confirmText: 'Delete',+ variant: 'danger',+ })+ if (!confirmed) return+ try {+ await unsubscribeListsApi.delete(list.id)+ notify.success('Unsubscribe list deleted')+ await goToPage(pageable.value.current_page)+ } catch {+ notify.error('Failed to delete unsubscribe list')+ }+}++function formatDate(dateStr: string): string {+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })+}++const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {+ closeModal()+})+</script>++<template>+ <div>+ <div class="page-header">+ <div style="display: flex; align-items: center; gap: 6px;">+ <h1>Unsubscribe Lists</h1>+ <button+ type="button"+ @click="showInfo = !showInfo"+ :title="showInfo ? 'Hide help' : 'How to use unsubscribe lists'"+ aria-label="Toggle help"+ style="background:transparent;border:0;cursor:pointer;color:var(--text-secondary,#6b7280);display:inline-flex;align-items:center;justify-content:center;padding:6px;border-radius:6px;"+ >+ <svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.5"/><path d="M9 12.75V9M9 5.25h.007" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>+ </button>+ </div>+ <button v-if="wsStore.canEdit" class="btn btn-primary" @click="openCreate">Add List</button>+ </div>++ <div v-if="showInfo" class="card" style="margin-bottom:16px;display:flex;gap:12px;align-items:flex-start;">+ <svg width="20" height="20" viewBox="0 0 18 18" fill="none" style="flex-shrink:0;color:#9333ea;margin-top:2px;"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.5"/><path d="M9 12.75V9M9 5.25h.007" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>+ <div style="flex:1;min-width:0;">+ <h3 style="margin-top:0;margin-bottom:8px;">Where to use Unsubscribe Lists</h3>+ <p style="margin:0 0 8px 0;">+ Reference a list from a transactional send with <code>unsubscribe.list_id</code>.<br>+ Posta mints the signed one-click URL and emits the <code>List-Unsubscribe</code> header.<br>+ A click opts the recipient out of <strong>that list only</strong> and their receipts, password resets, and other transactional mail keep flowing.+ </p>+ <pre class="code-block" style="margin:0;font-size:12px;line-height:1.5;"><code>POST /api/v1/emails/send+{+ "to": ["[email protected]"],+ "subject": "Product update",+ "html": "...",+ "unsubscribe": { "list_id": 42 }+}</code></pre>+ <p style="margin:10px 0 0 0;color:var(--text-secondary,#6b7280);font-size:13px;">+ Click a list name below to see who opted out and to resubscribe individual addresses.+ </p>+ </div>+ </div>++ <div v-if="loading" class="loading-page">+ <div class="spinner"></div>+ </div>++ <div v-else class="card">+ <div v-if="lists.length === 0" class="empty-state">+ <h3>No Unsubscribe Lists</h3>+ <p>Create a list, then reference it from a send with <code>unsubscribe.list_id</code>. A one-click then opts the recipient out of that list only.</p>+ </div>++ <template v-else>+ <div class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th>Name</th>+ <th>Public Name</th>+ <th>Description</th>+ <th>Status</th>+ <th>Created</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="list in lists" :key="list.id">+ <td>+ <a class="link" @click="router.push(`/unsubscribe-lists/${list.id}`)">{{ list.name }}</a>+ <span+ class="badge badge-neutral"+ :title="`Copy list ID ${list.id}`"+ style="cursor:pointer;user-select:none;"+ @click.stop="copyListId(list.id)"+ >#{{ list.id }}</span>+ </td>+ <td>{{ list.public_name || '—' }}</td>+ <td>{{ list.description || '—' }}</td>+ <td>+ <span v-if="list.active" class="badge badge-success">Active</span>+ <span v-else class="badge badge-neutral">Archived</span>+ </td>+ <td>{{ formatDate(list.created_at) }}</td>+ <td>+ <div class="flex gap-2">+ <button class="btn btn-secondary btn-sm" @click="router.push(`/unsubscribe-lists/${list.id}`)">View</button>+ <button v-if="wsStore.canEdit" class="btn btn-secondary btn-sm" @click="openEdit(list)">Edit</button>+ <button v-if="wsStore.canEdit" class="btn btn-danger btn-sm" @click="deleteList(list)">Delete</button>+ </div>+ </td>+ </tr>+ </tbody>+ </table>+ </div>++ <Pagination :pageable="pageable" @page="goToPage" />+ </template>+ </div>++ <!-- Create/Edit Unsubscribe List Modal -->+ <div v-if="showModal" class="modal-overlay" @mousedown="watchClickStart" @mouseup="confirmClickEnd">+ <div class="modal" style="max-width: 480px;" @mousedown.stop @mouseup.stop>+ <div class="modal-header">+ <h3>{{ editing ? 'Edit Unsubscribe List' : 'Add Unsubscribe List' }}</h3>+ </div>+ <div class="modal-body">+ <div class="form-group">+ <label class="form-label">Name</label>+ <input v-model="form.name" class="form-input" placeholder="e.g. Product updates" />+ <span class="form-hint">Internal label, unique within your account.</span>+ </div>+ <div class="form-group">+ <label class="form-label">Public name</label>+ <input v-model="form.public_name" class="form-input" placeholder="Shown to recipients (optional)" />+ <span class="form-hint">Displayed on the unsubscribe confirmation page. Falls back to the name.</span>+ </div>+ <div class="form-group">+ <label class="form-label">Description</label>+ <input v-model="form.description" class="form-input" placeholder="Optional" />+ </div>+ <div v-if="editing" class="form-group">+ <label class="checkbox-label">+ <input type="checkbox" v-model="form.active" />+ Active+ </label>+ <span class="form-hint">Archive a list to retire it without deleting its opt-out history.</span>+ </div>+ </div>+ <div class="modal-footer">+ <button class="btn btn-secondary" @click="closeModal">Cancel</button>+ <button class="btn btn-primary" :disabled="saving || !form.name.trim()" @click="saveList">+ {{ saving ? 'Saving...' : (editing ? 'Update' : 'Create') }}+ </button>+ </div>+ </div>+ </div>+ </div>+</template>diff --git a/web/src/views/webhooks/Webhooks.vue b/web/src/views/webhooks/Webhooks.vueindex dfc25e9..6dc31e7 100644--- a/web/src/views/webhooks/Webhooks.vue+++ b/web/src/views/webhooks/Webhooks.vue@@ -29,7 +29,7 @@ const createdWebhook = ref<Webhook | null>(null)const showSecretModal = ref(false)const copied = ref(false)-const availableEvents = ['email.sent', 'email.failed', 'email.inbound', 'campaign.started', 'campaign.completed']+const availableEvents = ['email.sent', 'email.failed', 'email.inbound', 'email.unsubscribed', 'email.complained', 'campaign.started', 'campaign.completed']const { pageable, goToPage } = usePagination(async (page) => {loading.value = true