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: add SMTP Relay
Mike Kosulind61e5dcc8b63
diff --git a/.env.example b/.env.exampleindex 9564763..7b51e75 100644--- a/.env.example+++ b/.env.example@@ -128,6 +128,23 @@ POSTA_INBOUND_TLS_MODE=nonePOSTA_INBOUND_SMTP_RATE_LIMIT=60# Rate-limit window in secondsPOSTA_INBOUND_SMTP_RATE_WINDOW=60++# SMTP Relay — lets a workspace issue SMTP credentials for migrating existing senders+# Master toggle — enables the SMTP relay listener and the /workspaces/current/smtp-credentials routes+POSTA_SMTP_RELAY_ENABLED=false+# Bind address for the built-in SMTP relay listener (plaintext, no TLS — not for public internet)+POSTA_SMTP_RELAY_HOST=0.0.0.0+# SMTP relay listener port (separate from POSTA_INBOUND_SMTP_PORT)+POSTA_SMTP_RELAY_PORT=2526+# Hostname announced in EHLO+POSTA_SMTP_RELAY_HOSTNAME=posta.example.com+# Max raw message size in bytes (default 25 MiB)+POSTA_SMTP_RELAY_MAX_MESSAGE_SIZE=26214400+# Per-IP SMTP rate limit: max sessions per window (0 disables)+POSTA_SMTP_RELAY_RATE_LIMIT=60+# Rate-limit window in seconds+POSTA_SMTP_RELAY_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=falsediff --git a/cmd/posta/server.go b/cmd/posta/server.goindex a5950c3..61a4934 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -39,6 +39,7 @@ import ("github.com/goposta/posta/internal/services/retry""github.com/goposta/posta/internal/services/seeder""github.com/goposta/posta/internal/services/settings"+ "github.com/goposta/posta/internal/services/smtprelay""github.com/goposta/posta/internal/services/tracking""github.com/goposta/posta/internal/services/webhook""github.com/goposta/posta/internal/services/workermon"@@ -63,6 +64,7 @@ type serverResources struct {db *gorm.DBredis *redis.ClientsmtpInbound *smtp.Server+ smtpRelay *smtp.Server}func runServer(cli *okapicli.CLI) {@@ -163,7 +165,7 @@ func runServer(cli *okapicli.CLI) {res.cronManager = initCronManager(res.db, cfg, notifier, res.blobStore, res.producer)}- routes.InitRoutes(app, res.db,+ emailSvc := routes.InitRoutes(app, res.db,res.redis,cfg,res.producer,@@ -171,6 +173,14 @@ func runServer(cli *okapicli.CLI) {res.blobStore,context.Background(), notifier)+ if cfg.SMTPRelayEnabled && !cfg.DevMode {+ if srv, err := startSMTPRelayServer(res.db, cfg, emailSvc); err != nil {+ logger.Error("failed to start SMTP relay server", "error", err)+ } else {+ res.smtpRelay = srv+ }+ }+if res.cronManager != nil {res.cronManager.Start(context.Background())}@@ -325,6 +335,37 @@ func startInboundSMTPServer(return srv, nil}+// startSMTPRelayServer configures and launches the built-in SMTP Relay+// (AUTH-gated relay) listener. Returns the server so it can be+// gracefully shut down on exit.+func startSMTPRelayServer(db *gorm.DB, cfg *config.Config, emailSvc *email.Service) (*smtp.Server, error) {+ credRepo := repositories.NewSMTPCredentialRepository(db)+ userRepo := repositories.NewUserRepository(db)+ backend := smtprelay.NewBackend(credRepo, userRepo, emailSvc, cfg.SMTPRelayMaxMessageSize)+ if cfg.SMTPRelayRateLimit > 0 {+ window := time.Duration(cfg.SMTPRelayRateWindow) * time.Second+ backend.SetRateLimiter(inbound.NewIPRateLimiter(cfg.SMTPRelayRateLimit, window))+ }+ srv, err := smtprelay.NewSMTPServer(backend, smtprelay.SMTPConfig{+ Host: cfg.SMTPRelayHost,+ Port: cfg.SMTPRelayPort,+ Hostname: cfg.SMTPRelayHostname,+ MaxMessageSize: cfg.SMTPRelayMaxMessageSize,+ })+ if err != nil {+ return nil, err+ }++ go func() {+ logger.Info("SMTP relay server listening", "addr", srv.Addr)+ err := srv.ListenAndServe()+ if err != nil && !errors.Is(err, net.ErrClosed) && !errors.Is(err, smtp.ErrServerClosed) {+ logger.Error("SMTP relay server error", "error", err)+ }+ }()+ return srv, nil+}+// startEmbeddedWorker starts an in-process asynq worker for email delivery.// The bus argument is used by the inbound parse handler to publish// email.inbound.received events; it may be nil when inbound is disabled.@@ -526,6 +567,13 @@ func shutdownServer(res *serverResources) {}cancel()}+ if res.smtpRelay != nil {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ if err := res.smtpRelay.Shutdown(ctx); err != nil {+ logger.Error("failed to shut down SMTP relay server", "error", err)+ }+ cancel()+ }if res.cronManager != nil {res.cronManager.Stop()}diff --git a/docs/docs/security/rate-limiting.md b/docs/docs/security/rate-limiting.mdindex 2229ab4..ed336da 100644--- a/docs/docs/security/rate-limiting.md+++ b/docs/docs/security/rate-limiting.md@@ -1,5 +1,5 @@----sidebar_position: 4+sidebar_position: 5title: Rate Limitingdescription: Email and API rate limits---diff --git a/docs/docs/security/sessions.md b/docs/docs/security/sessions.mdindex 84a83da..450bf56 100644--- a/docs/docs/security/sessions.md+++ b/docs/docs/security/sessions.md@@ -1,5 +1,5 @@----sidebar_position: 5+sidebar_position: 6title: Session Managementdescription: Manage active sessions---diff --git a/docs/docs/security/smtp-relay.md b/docs/docs/security/smtp-relay.mdnew file mode 100644index 0000000..d03d70c--- /dev/null+++ b/docs/docs/security/smtp-relay.md@@ -0,0 +1,165 @@+---+sidebar_position: 3+title: SMTP Relay+description: Relay mail from an existing SMTP sender through Posta's outbound pipeline+---++# SMTP Relay++The SMTP Relay is a migration aid for teams that already send mail through an SMTP client or library and are not yet ready to rewrite that integration against the HTTP API. A workspace issues SMTP username/password credentials from Posta, the existing SMTP client points at Posta's SMTP Relay instead of its current outbound provider, and every message it sends is parsed and relayed through the **same outbound pipeline** used by `POST /api/v1/emails/send` — the same domain-verification, suppression-list, rate-limit, and delivery handling, just reached over SMTP instead of HTTP. Teams can cut over their SMTP client on day one and migrate call sites to the HTTP API gradually, at their own pace.++This is a separate, purpose-built listener from [Inbound Email](../inbound/overview.md): Inbound accepts anonymous mail addressed to a verified domain, while the Relay requires SMTP AUTH and exists to accept mail *from* your applications, independent of whether Inbound is enabled.++## Enabling the Relay++The SMTP Relay is off by default. Enable it with configuration:++| Variable | Default | Description |+|----------|---------|--------------|+| `POSTA_SMTP_RELAY_ENABLED` | `false` | Master switch. Enables the SMTP relay listener and the `/api/v1/workspaces/current/smtp-credentials` routes. |+| `POSTA_SMTP_RELAY_HOST` | `0.0.0.0` | Bind address for the built-in SMTP relay listener. |+| `POSTA_SMTP_RELAY_PORT` | `2526` | Listener port. Separate from `POSTA_INBOUND_SMTP_PORT` — the two listeners never share a port or process state. |+| `POSTA_SMTP_RELAY_HOSTNAME` | `posta.local` | Hostname announced in the SMTP `EHLO` greeting. |+| `POSTA_SMTP_RELAY_MAX_MESSAGE_SIZE` | `26214400` (25 MiB) | Maximum raw message size in bytes. Larger messages are rejected with `552`. |+| `POSTA_SMTP_RELAY_RATE_LIMIT` | `60` | Per-IP maximum SMTP sessions per window; `0` disables the limit. |+| `POSTA_SMTP_RELAY_RATE_WINDOW` | `60` | Rate-limit window, in seconds. |++:::danger No TLS+The Relay listener does **not** support TLS or STARTTLS, by design — it is a minimal, plaintext-AUTH migration aid, not a hardened public MTA. Credentials and message content travel unencrypted. Only expose `POSTA_SMTP_RELAY_PORT` on a private network, over a VPN, or to `localhost` — never bind it directly to the public internet. If you need Relay access from outside your private network, put a TLS-terminating TCP proxy (e.g. stunnel, an SMTP-aware load balancer) in front of it; Posta itself will never decrypt or negotiate TLS on this listener.+:::++## How It Works++```+your SMTP client POSTA_SMTP_RELAY_PORT (no TLS)+ │ │+ ├── EHLO / AUTH PLAIN ────────────►│ verify SMTPCredential (workspace-scoped)+ │ │+ └── MAIL FROM / RCPT TO / DATA ───►│ parse message+ │+ ▼+ email.Service.Send() ──► same pipeline as POST /api/v1/emails/send+ │+ ├─► domain verification+ ├─► suppression list+ ├─► rate limits / plan quota+ └─► queued for delivery (Email record)+```++1. Your SMTP client opens a connection to `POSTA_SMTP_RELAY_HOST:POSTA_SMTP_RELAY_PORT` and authenticates with `AUTH PLAIN`, using an SMTP Relay username and password.+2. Posta looks up the credential, confirms it is not revoked, and ties the rest of the session to the credential's workspace. `MAIL FROM`, `RCPT TO`, and `DATA` are all rejected until AUTH succeeds.+3. On `DATA`, Posta reads the raw message (bounded by `POSTA_SMTP_RELAY_MAX_MESSAGE_SIZE`), parses subject, HTML/text bodies, and attachments from the MIME body, and builds a send request using the SMTP envelope addresses (`MAIL FROM` / `RCPT TO`) rather than the parsed header addresses — the same behavior a normal MTA would have.+4. That request is handed to the same `email.Service.Send` used by the HTTP API, scoped to the credential's workspace and owning user. It goes through the identical checks: sender domain verification, suppression-list filtering, rate limits, plan quota, and attachment-size validation, and a normal `Email` record is created and queued for delivery.+5. The SMTP response code reflects the outcome of that call — see [Send Outcomes](#send-outcomes) below.++## Issuing a Credential++SMTP credentials are workspace-scoped and always require a workspace — there is no personal/unscoped credential. Create one from the dashboard under **Developers → SMTP Relay** (`/smtp-relay`), or directly via the API:++```+POST /api/v1/workspaces/current/smtp-credentials+```++```bash+curl -X POST http://localhost:9000/api/v1/workspaces/current/smtp-credentials \+ -H "Authorization: Bearer <jwt>" \+ -H "X-Posta-Workspace-Id: 1" \+ -H "Content-Type: application/json" \+ -d '{ "name": "Legacy app relay", "allowed_ips": ["203.0.113.0/24"] }'+```++Response (`201`):++```json+{+ "success": true,+ "data": {+ "id": 7,+ "name": "Legacy app relay",+ "username": "smtp_9f3c2a1b7e4d5601",+ "password": "8b1c...e02f",+ "host": "posta.local",+ "port": 2526,+ "created_at": "2026-07-20T00:00:00Z",+ "message": "Save this password securely. It will not be shown again."+ }+}+```++:::warning+**Save the password immediately.** Like an API key, the plaintext password is only returned once, at creation time. Posta stores only a hash of it.+:::++Unlike API keys, an SMTP credential has no expiry or scopes — it is either usable or revoked. It does support an IP allowlist (`allowed_ips`), same as [API keys](./api-keys.md#security-features): an empty list permits any IP.++### Listing Credentials++```+GET /api/v1/workspaces/current/smtp-credentials+```++Returns a paginated list scoped to the current workspace. Passwords are never returned — only credential metadata (`id`, `name`, `username`, `allowed_ips`, `revoked`, `created_at`, `last_used_at`).++### Revoking a Credential++Instantly disables a credential without deleting it, mirroring [API key revocation](./api-keys.md#revoking-a-key):++```+POST /api/v1/workspaces/current/smtp-credentials/{id}/revoke+```++A revoked credential fails `AUTH` immediately on its next connection attempt; any already-open session is not forcibly disconnected but subsequent commands on a *new* session will be rejected.++### Deleting a Credential++```+DELETE /api/v1/workspaces/current/smtp-credentials/{id}+```++Permanently removes the credential record.++## Connecting Your SMTP Client++Point your existing SMTP client at the Relay host and port, with the generated username/password and no encryption:++| Setting | Value |+|---|---|+| Host | `POSTA_SMTP_RELAY_HOST` (or wherever it's reachable from your app) |+| Port | `POSTA_SMTP_RELAY_PORT` (default `2526`) |+| Encryption | None — do not configure TLS or STARTTLS on the client |+| Auth mechanism | `PLAIN` |+| Username / Password | From the credential creation response |++```bash+swaks --server localhost --port 2526 \+ --auth PLAIN --auth-user smtp_9f3c2a1b7e4d5601 --auth-password 8b1c...e02f \+ --from [email protected] --to [email protected] \+ --header "Subject: Hello from the SMTP Relay" \+ --body "This message was relayed through Posta's outbound pipeline."+```++`AUTH PLAIN` is the only mechanism the Relay advertises; clients that default to `LOGIN` or `CRAM-MD5` should be configured to use `PLAIN` explicitly. The listener accepts up to 50 recipients per message.++## Send Outcomes++Because the Relay relays into the same `email.Service.Send` used by `POST /api/v1/emails/send`, an accepted message ends up in the identical set of [email statuses](../email-sending/email-status.md#status-values) (`pending`, `queued`, `processing`, `sent`, `failed`, `suppressed`) — the Relay does not introduce any new ones. The SMTP response code the client sees just reflects whether Posta accepted the message for that pipeline, not its eventual delivery outcome:++| SMTP response | Meaning |+|---|---|+| `250` | Accepted and handed to the outbound pipeline as an `Email` record. This includes the case where every recipient was suppressed — Posta still accepts the message, logs it with `suppressed` status, and does not attempt delivery, exactly as the HTTP API does. |+| `550 5.7.1` | Sender domain is not [verified](../smtp-domains/domain-verification.md) for this workspace. |+| `452 4.7.0` / `421 4.7.0` | [Rate limit](./rate-limiting.md) or plan quota exceeded; retry later. |+| `552 5.3.4` | Message exceeds `POSTA_SMTP_RELAY_MAX_MESSAGE_SIZE`. |+| `554 5.6.0` | Message could not be parsed (malformed MIME). |+| `451 4.3.0` | Temporary failure (e.g. a transient error while queuing). |+| `502 5.7.0` | A mail command was sent before a successful `AUTH`. |+| `535 5.7.8` | `AUTH` failed — unknown or revoked credential, wrong password, inactive user, or the connecting IP is not on the credential's `allowed_ips`. |++Check the eventual delivery outcome of a message the same way you would for an API-sent email — via `GET /api/v1/emails/{id}/status` using the `id` Posta assigned, or by browsing the workspace's email log in the dashboard.++## Next Steps++- [Domain Verification](../smtp-domains/domain-verification.md) — required before a sender address can relay mail.+- [API Keys](./api-keys.md) — the HTTP-API equivalent of a Relay credential, for when you're ready to migrate fully.+- [Rate Limiting](./rate-limiting.md) — how send limits are enforced across both the HTTP API and the Relay.+- [Email Status](../email-sending/email-status.md) — track a relayed message after it's accepted.diff --git a/docs/docs/security/two-factor-auth.md b/docs/docs/security/two-factor-auth.mdindex 28db57c..e985d60 100644--- a/docs/docs/security/two-factor-auth.md+++ b/docs/docs/security/two-factor-auth.md@@ -1,5 +1,5 @@----sidebar_position: 3+sidebar_position: 4title: Two-Factor Authenticationdescription: TOTP-based two-factor authentication---diff --git a/docs/sidebars.ts b/docs/sidebars.tsindex 55489ed..c9dd850 100644--- a/docs/sidebars.ts+++ b/docs/sidebars.ts@@ -74,6 +74,7 @@ const sidebars: SidebarsConfig = {items: ['security/authentication','security/api-keys',+ 'security/smtp-relay','security/two-factor-auth','security/rate-limiting','security/sessions',diff --git a/go.mod b/go.modindex 66e988e..842d483 100644--- a/go.mod+++ b/go.mod@@ -7,6 +7,7 @@ require (github.com/aws/aws-sdk-go-v2/credentials v1.19.28github.com/aws/aws-sdk-go-v2/service/s3 v1.105.2github.com/coreos/go-oidc/v3 v3.20.0+ github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6github.com/emersion/go-smtp v0.24.0github.com/golang-jwt/jwt/v5 v5.3.1github.com/google/uuid v1.6.0@@ -47,7 +48,6 @@ require (github.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/clipperhouse/displaywidth v0.11.0 // indirectgithub.com/clipperhouse/uax29/v2 v2.7.0 // indirect- github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirectgithub.com/fatih/color v1.19.0 // indirectgithub.com/getkin/kin-openapi v0.140.0 // indirectgithub.com/go-jose/go-jose/v4 v4.1.4 // indirectdiff --git a/internal/config/config.go b/internal/config/config.goindex add6be7..c7af07d 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -123,6 +123,15 @@ type Config struct {InboundTLSKeyFile stringInboundSMTPRateLimit int // per-IP max sessions per window; 0 disablesInboundSMTPRateWindow int // rate-limit window in seconds++ // SMTP Relay settings. No TLS by design.+ SMTPRelayEnabled bool+ SMTPRelayHost string+ SMTPRelayPort int+ SMTPRelayHostname string+ SMTPRelayMaxMessageSize int64+ SMTPRelayRateLimit int+ SMTPRelayRateWindow int}type SystemSMTPConfig struct {Host string@@ -305,6 +314,14 @@ func New() *Config {InboundTLSKeyFile: goutils.Env("POSTA_INBOUND_TLS_KEY_FILE", ""),InboundSMTPRateLimit: goutils.EnvInt("POSTA_INBOUND_SMTP_RATE_LIMIT", 60),InboundSMTPRateWindow: goutils.EnvInt("POSTA_INBOUND_SMTP_RATE_WINDOW", 60),++ SMTPRelayEnabled: goutils.EnvBool("POSTA_SMTP_RELAY_ENABLED", false),+ SMTPRelayHost: goutils.Env("POSTA_SMTP_RELAY_HOST", "0.0.0.0"),+ SMTPRelayPort: goutils.EnvInt("POSTA_SMTP_RELAY_PORT", 2526),+ SMTPRelayHostname: goutils.Env("POSTA_SMTP_RELAY_HOSTNAME", "posta.local"),+ SMTPRelayMaxMessageSize: int64(goutils.EnvInt("POSTA_SMTP_RELAY_MAX_MESSAGE_SIZE", 26214400)),+ SMTPRelayRateLimit: goutils.EnvInt("POSTA_SMTP_RELAY_RATE_LIMIT", 60),+ SMTPRelayRateWindow: goutils.EnvInt("POSTA_SMTP_RELAY_RATE_WINDOW", 60),}}func (c *Config) validate() error {diff --git a/internal/dto/types.go b/internal/dto/types.goindex 67751db..4a9852d 100644--- a/internal/dto/types.go+++ b/internal/dto/types.go@@ -17,6 +17,8 @@package dto+import "time"+// Response is the standard API response envelope with a generic data field.type Response[T any] struct {Success bool `json:"success"`@@ -65,3 +67,14 @@ type APIKeyCreatedData struct {type MessageData struct {Message string `json:"message"`}++type SMTPCredentialCreatedData struct {+ ID uint `json:"id"`+ Name string `json:"name"`+ Username string `json:"username"`+ Password string `json:"password"`+ Host string `json:"host"`+ Port int `json:"port"`+ CreatedAt time.Time `json:"created_at"`+ Message string `json:"message"`+}diff --git a/internal/handlers/smtp_credential_handler.go b/internal/handlers/smtp_credential_handler.gonew file mode 100644index 0000000..7587f0f--- /dev/null+++ b/internal/handlers/smtp_credential_handler.go@@ -0,0 +1,140 @@+/*+ * 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 (+ "github.com/goposta/posta/internal/config"+ "github.com/goposta/posta/internal/services/smtprelay"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/okapi"+)++type SMTPCredentialHandler struct {+ service *smtprelay.CredentialService+ repo *repositories.SMTPCredentialRepository+ cfg *config.Config+}++func NewSMTPCredentialHandler(service *smtprelay.CredentialService, repo *repositories.SMTPCredentialRepository, cfg *config.Config) *SMTPCredentialHandler {+ return &SMTPCredentialHandler{+ service: service,+ repo: repo,+ cfg: cfg,+ }+}++type CreateSMTPCredentialRequest struct {+ Body struct {+ Name string `json:"name" required:"true"`+ AllowedIPs []string `json:"allowed_ips"`+ } `json:"body"`+}++type GetSMTPCredentialRequest struct {+ ID int `param:"id" doc:"SMTP credential ID"`+}++type RevokeSMTPCredentialRequest struct {+ ID int `param:"id"`+}++type DeleteSMTPCredentialRequest struct {+ ID int `param:"id"`+}++func (h *SMTPCredentialHandler) Create(c *okapi.Context, req *CreateSMTPCredentialRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("Insufficient workspace permissions", err)+ }+ scope := getScope(c)+ if scope.WorkspaceID == nil {+ return c.AbortBadRequest("a workspace is required to create SMTP credentials")+ }++ username, password, cred, err := h.service.GenerateCredential(scope.UserID, *scope.WorkspaceID, req.Body.Name, req.Body.AllowedIPs)+ if err != nil {+ return c.AbortInternalServerError("failed to create SMTP credential", err)+ }++ return created(c, okapi.M{+ "id": cred.ID,+ "name": cred.Name,+ "username": username,+ "password": password,+ "host": h.cfg.SMTPRelayHostname,+ "port": h.cfg.SMTPRelayPort,+ "created_at": cred.CreatedAt,+ "message": "Save this password securely. It will not be shown again.",+ })+}++func (h *SMTPCredentialHandler) List(c *okapi.Context, req *ListRequest) error {+ page, size, offset := normalizePageParams(req.Page, req.Size)++ scope := getScope(c)+ if scope.WorkspaceID == nil {+ return c.AbortBadRequest("a workspace is required to list SMTP credentials")+ }++ creds, total, err := h.repo.FindByWorkspaceID(*scope.WorkspaceID, size, offset)+ if err != nil {+ return c.AbortInternalServerError("failed to list SMTP credentials")+ }++ return paginated(c, creds, total, page, size)+}++func (h *SMTPCredentialHandler) Get(c *okapi.Context, req *GetSMTPCredentialRequest) error {+ cred, err := h.repo.FindByID(uint(req.ID))+ if err != nil || !ownsResource(c, cred.UserID, &cred.WorkspaceID) {+ return c.AbortNotFound("SMTP credential not found")+ }+ return ok(c, cred)+}++func (h *SMTPCredentialHandler) Revoke(c *okapi.Context, req *RevokeSMTPCredentialRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("Insufficient workspace permissions", err)+ }+ cred, err := h.repo.FindByID(uint(req.ID))+ if err != nil || !ownsResource(c, cred.UserID, &cred.WorkspaceID) {+ return c.AbortNotFound("SMTP credential not found")+ }++ if err := h.repo.Revoke(cred.ID); err != nil {+ return c.AbortInternalServerError("failed to revoke SMTP credential")+ }++ return ok(c, okapi.M{"message": "SMTP credential revoked"})+}++func (h *SMTPCredentialHandler) Delete(c *okapi.Context, req *DeleteSMTPCredentialRequest) error {+ if err := requireEdit(c); err != nil {+ return c.AbortForbidden("Insufficient workspace permissions", err)+ }+ cred, err := h.repo.FindByID(uint(req.ID))+ if err != nil || !ownsResource(c, cred.UserID, &cred.WorkspaceID) {+ return c.AbortNotFound("SMTP credential not found")+ }++ if err := h.repo.Delete(cred.ID); err != nil {+ return c.AbortInternalServerError("failed to delete SMTP credential")+ }++ return ok(c, okapi.M{"message": "SMTP credential deleted"})+}diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.goindex 203107c..88877bd 100644--- a/internal/middlewares/middleware.go+++ b/internal/middlewares/middleware.go@@ -233,7 +233,7 @@ func authenticateAPIKey(c *okapi.Context, keyService *auth.APIKeyService, userReif !user.Active {return c.AbortForbidden("account is disabled")}- if !ipAllowed(apiKey.AllowedIPs, c.RealIP()) {+ if !IPAllowed(apiKey.AllowedIPs, c.RealIP()) {return c.AbortForbidden("IP address not allowed for this API key")}@@ -262,9 +262,9 @@ func authenticateAPIKey(c *okapi.Context, keyService *auth.APIKeyService, userRereturn c.Next()}-// ipAllowed reports whether clientIP is permitted by an API key's allowlist. An+// IPAllowed reports whether clientIP is permitted by an API key's allowlist. An// empty allowlist permits any IP; entries may be exact IPs or CIDR ranges.-func ipAllowed(allowed []string, clientIP string) bool {+func IPAllowed(allowed []string, clientIP string) bool {if len(allowed) == 0 {return true}diff --git a/internal/models/smtp_credential.go b/internal/models/smtp_credential.gonew file mode 100644index 0000000..d10f952--- /dev/null+++ b/internal/models/smtp_credential.go@@ -0,0 +1,43 @@+/*+ * 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"++ "github.com/lib/pq"+)++type SMTPCredential struct {+ ID uint `json:"id" gorm:"primaryKey"`+ WorkspaceID uint `json:"workspace_id" gorm:"index;not null"`+ UserID uint `json:"user_id" gorm:"index;not null"` // creator, for audit+ Name string `json:"name" gorm:"not null"`+ Username string `json:"username" gorm:"uniqueIndex;not null"`+ PasswordHash string `json:"-" gorm:"not null"`+ AllowedIPs pq.StringArray `json:"allowed_ips" gorm:"type:text[]"`+ Revoked bool `json:"revoked" gorm:"default:false"`+ CreatedAt time.Time `json:"created_at"`+ LastUsedAt *time.Time `json:"last_used_at"`++ User User `json:"-" gorm:"foreignKey:UserID"`+}++func (k *SMTPCredential) IsValid() bool {+ return !k.Revoked+}diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 2f9a629..c078bb9 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -41,6 +41,7 @@ import ("github.com/goposta/posta/internal/services/seeder"sessionpkg "github.com/goposta/posta/internal/services/session""github.com/goposta/posta/internal/services/settings"+ "github.com/goposta/posta/internal/services/smtprelay""github.com/goposta/posta/internal/services/tracking""github.com/goposta/posta/internal/services/verifier""github.com/goposta/posta/internal/services/webhook"@@ -122,10 +123,11 @@ type routerHandlers struct {workspaceData *handlers.WorkspaceDataHandlerplan *handlers.PlanHandlerinbound *handlers.InboundHandler+ smtpCredential *handlers.SMTPCredentialHandlerverify *handlers.VerifyHandler}-func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) {+func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) *email.Service {repositories.SetWorkspaceOnlyMode(cfg.WorkspaceOnlyMode)@@ -394,6 +396,13 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cr.h.inbound.SetEventBus(bus)}+ // SMTP Relay+ if cfg.SMTPRelayEnabled {+ smtpCredRepo := repositories.NewSMTPCredentialRepository(db)+ credService := smtprelay.NewCredentialService(smtpCredRepo)+ r.h.smtpCredential = handlers.NewSMTPCredentialHandler(credService, smtpCredRepo, cfg)+ }+// Workspace data export/importr.h.workspaceData = handlers.NewWorkspaceDataHandler(db, workspaceRepo, templateRepo, versionRepo, localizationRepo,@@ -419,6 +428,8 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c}r.registerRoutes()++ return emailService}// emailPlanAdapter adapts planpkg.Service to the email.PlanLimitsProvider interface.@@ -476,7 +487,6 @@ func (r *Router) registerRoutes() {r.app.Register(r.inboundWebhookRoutes()...)r.app.Register(r.inboundWorkspaceRoutes()...)}-r.app.Register(r.adminSSERoutes()...)r.app.Register(r.adminRoutes()...)diff --git a/internal/routes/workspace_resource_routes.go b/internal/routes/workspace_resource_routes.goindex ca16d08..9d3a6a2 100644--- a/internal/routes/workspace_resource_routes.go+++ b/internal/routes/workspace_resource_routes.go@@ -195,6 +195,75 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),},},+ }++ if r.cfg.SMTPRelayEnabled {+ routes = append(routes,+ okapi.RouteDefinition{+ Method: http.MethodPost,+ Path: "/smtp-credentials",+ Handler: okapi.H(r.h.smtpCredential.Create),+ Group: opsGroup,+ Summary: "Create an SMTP Relay credential",+ Description: "Generate a new SMTP username/password credential for this workspace. " ++ "The raw password is only shown once in the response.",+ Request: &handlers.CreateSMTPCredentialRequest{},+ Options: []okapi.RouteOption{+ okapi.DocResponse(201, &dto.Response[dto.SMTPCredentialCreatedData]{}),+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),+ },+ },+ okapi.RouteDefinition{+ Method: http.MethodGet,+ Path: "/smtp-credentials",+ Handler: okapi.H(r.h.smtpCredential.List),+ Group: opsGroup,+ Summary: "List SMTP Relay credentials",+ Request: &handlers.ListRequest{},+ Response: &dto.PageableResponse[models.SMTPCredential]{},+ },+ okapi.RouteDefinition{+ Method: http.MethodGet,+ Path: "/smtp-credentials/{id:int}",+ Handler: okapi.H(r.h.smtpCredential.Get),+ Group: opsGroup,+ Summary: "Get an SMTP Relay credential",+ Request: &handlers.GetSMTPCredentialRequest{},+ Response: &dto.Response[models.SMTPCredential]{},+ Options: []okapi.RouteOption{+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),+ },+ },+ okapi.RouteDefinition{+ Method: http.MethodPost,+ Path: "/smtp-credentials/{id:int}/revoke",+ Handler: okapi.H(r.h.smtpCredential.Revoke),+ Group: opsGroup,+ Summary: "Revoke an SMTP Relay credential",+ Request: &handlers.RevokeSMTPCredentialRequest{},+ Response: &dto.Response[dto.MessageData]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "SMTP credential ID"),+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),+ },+ },+ okapi.RouteDefinition{+ Method: http.MethodDelete,+ Path: "/smtp-credentials/{id:int}",+ Handler: okapi.H(r.h.smtpCredential.Delete),+ Group: opsGroup,+ Summary: "Delete an SMTP Relay credential",+ Request: &handlers.DeleteSMTPCredentialRequest{},+ Response: &dto.Response[dto.MessageData]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "SMTP credential ID"),+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),+ },+ },+ )+ }++ routes = append(routes, []okapi.RouteDefinition{{Method: http.MethodPost,Path: "/templates",@@ -1162,7 +1231,7 @@ func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {Response: &dto.PageableResponse[models.CampaignMessage]{},Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Campaign ID")},},- }+ }...)return routes}diff --git a/internal/services/smtprelay/backend.go b/internal/services/smtprelay/backend.gonew file mode 100644index 0000000..32ccb63--- /dev/null+++ b/internal/services/smtprelay/backend.go@@ -0,0 +1,222 @@+/*+ * 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 smtprelay++import (+ "context"+ "encoding/base64"+ "io"+ "net"+ "net/mail"+ "strings"+ "time"++ "github.com/emersion/go-sasl"+ "github.com/emersion/go-smtp"+ "github.com/goposta/posta/internal/middlewares"+ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/email"+ "github.com/goposta/posta/internal/services/inbound"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/logger"+)++type Backend struct {+ credRepo *repositories.SMTPCredentialRepository+ userRepo *repositories.UserRepository+ emailSvc *email.Service+ maxMessageSize int64+ limiter *inbound.IPRateLimiter+}++func NewBackend(credRepo *repositories.SMTPCredentialRepository, userRepo *repositories.UserRepository, emailSvc *email.Service, maxMessageSize int64) *Backend {+ return &Backend{+ credRepo: credRepo,+ userRepo: userRepo,+ emailSvc: emailSvc,+ maxMessageSize: maxMessageSize,+ }+}++// SetRateLimiter enables per-IP rate limiting for new SMTP sessions.+func (b *Backend) SetRateLimiter(l *inbound.IPRateLimiter) { b.limiter = l }++func (b *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) {+ remote := c.Conn().RemoteAddr().String()+ if b.limiter != nil {+ ip := remote+ if host, _, err := net.SplitHostPort(remote); err == nil {+ ip = host+ }+ if !b.limiter.Allow(ip) {+ logger.Warn("smtp relay: rate-limited remote", "ip", ip)+ return nil, &smtp.SMTPError{Code: 421, EnhancedCode: smtp.EnhancedCode{4, 7, 0}, Message: "rate limit exceeded"}+ }+ }+ return &session{+ backend: b,+ remote: remote,+ }, nil+}++// credential stays non-nil for the connection's lifetime once AUTH succeeds; Reset does not clear it.+type session struct {+ backend *Backend+ remote string+ credential *models.SMTPCredential+ ownerEmail string+ from string+ to []string+}++func (s *session) AuthMechanisms() []string { return []string{sasl.Plain} }++func (s *session) Auth(mech string) (sasl.Server, error) {+ if mech != sasl.Plain {+ return nil, smtp.ErrAuthUnknownMechanism+ }+ return sasl.NewPlainServer(func(identity, username, password string) error {+ cred, err := s.backend.credRepo.FindByUsername(username)+ if err != nil || cred == nil || !cred.IsValid() {+ return smtp.ErrAuthFailed+ }+ if !VerifyPassword(cred, password) {+ return smtp.ErrAuthFailed+ }+ ip := s.remote+ if host, _, err := net.SplitHostPort(s.remote); err == nil {+ ip = host+ }+ if !middlewares.IPAllowed(cred.AllowedIPs, ip) {+ return smtp.ErrAuthFailed+ }+ owner, err := s.backend.userRepo.FindByID(cred.UserID)+ if err != nil || !owner.Active {+ return smtp.ErrAuthFailed+ }++ s.credential = cred+ s.ownerEmail = owner.Email+ go func() { _ = s.backend.credRepo.UpdateLastUsed(cred.ID) }()+ return nil+ }), nil+}++func (s *session) Reset() {+ s.from = ""+ s.to = nil+}++func (s *session) Logout() error { return nil }++func (s *session) Mail(from string, _ *smtp.MailOptions) error {+ if s.credential == nil {+ return smtp.ErrAuthRequired+ }+ if from != "" {+ if addr, err := mail.ParseAddress(from); err == nil {+ s.from = addr.Address+ } else {+ s.from = from+ }+ }+ return nil+}++func (s *session) Rcpt(to string, _ *smtp.RcptOptions) error {+ if s.credential == nil {+ return smtp.ErrAuthRequired+ }+ addr := to+ if parsed, err := mail.ParseAddress(to); err == nil {+ addr = parsed.Address+ }+ s.to = append(s.to, addr)+ return nil+}++// Data reads the raw message (bounded by MaxMessageSize), parses it, and+// relays it through the outbound email pipeline using the SMTP envelope+// (MAIL FROM / RCPT TO) rather than the parsed header addresses, matching+// normal MTA behavior.+func (s *session) Data(r io.Reader) error {+ if s.credential == nil {+ return smtp.ErrAuthRequired+ }++ limit := s.backend.maxMessageSize+ if limit <= 0 {+ limit = 26214400+ }+ // +1 to detect overflow.+ lr := &io.LimitedReader{R: r, N: limit + 1}+ raw, err := io.ReadAll(lr)+ if err != nil {+ return &smtp.SMTPError{Code: 451, EnhancedCode: smtp.EnhancedCode{4, 3, 0}, Message: "read error"}+ }+ if int64(len(raw)) > limit {+ return &smtp.SMTPError{Code: 552, EnhancedCode: smtp.EnhancedCode{5, 3, 4}, Message: "message size exceeds limit"}+ }++ parsed, perr := inbound.ParseRawEmail(raw)+ if perr != nil {+ return &smtp.SMTPError{Code: 554, EnhancedCode: smtp.EnhancedCode{5, 6, 0}, Message: "malformed message"}+ }++ attachments := make([]models.Attachment, 0, len(parsed.Attachments))+ for _, a := range parsed.Attachments {+ attachments = append(attachments, models.Attachment{+ Filename: a.Filename,+ ContentType: a.ContentType,+ Content: base64.StdEncoding.EncodeToString(a.Content),+ })+ }++ req := &email.SendRequest{+ From: s.from,+ To: s.to,+ Subject: parsed.Subject,+ HTML: parsed.HTMLBody,+ Text: parsed.TextBody,+ Attachments: attachments,+ }++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ _, serr := s.backend.emailSvc.Send(ctx, s.credential.UserID, 0, &s.credential.WorkspaceID, s.ownerEmail, req)+ return mapSendError(serr, s.remote)+}++// mapSendError translates an error returned by email.Service.Send into the+// appropriate SMTP status for the submitting client.+func mapSendError(err error, remote string) error {+ if err == nil {+ return nil+ }+ msg := err.Error()+ switch {+ case strings.HasPrefix(msg, "rate_limit:"):+ return &smtp.SMTPError{Code: 452, EnhancedCode: smtp.EnhancedCode{4, 7, 0}, Message: "rate limit exceeded, try again later"}+ case strings.HasPrefix(msg, "domain_verification:"):+ return &smtp.SMTPError{Code: 550, EnhancedCode: smtp.EnhancedCode{5, 7, 1}, Message: "sender domain not verified for this workspace"}+ default:+ logger.Error("smtp relay: send failed", "remote", remote, "error", err)+ return &smtp.SMTPError{Code: 451, EnhancedCode: smtp.EnhancedCode{4, 3, 0}, Message: "temporary failure"}+ }+}diff --git a/internal/services/smtprelay/backend_test.go b/internal/services/smtprelay/backend_test.gonew file mode 100644index 0000000..f068029--- /dev/null+++ b/internal/services/smtprelay/backend_test.go@@ -0,0 +1,58 @@+/*+ * 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 smtprelay++import (+ "errors"+ "testing"++ "github.com/emersion/go-smtp"+)++func TestMapSendError(t *testing.T) {+ tests := []struct {+ name string+ err error+ wantNil bool+ wantCode int+ }{+ {name: "nil error accepted", err: nil, wantNil: true},+ {name: "rate limit", err: errors.New("rate_limit: too many requests"), wantCode: 452},+ {name: "domain verification", err: errors.New("domain_verification: sender domain not verified"), wantCode: 550},+ {name: "other error", err: errors.New("boom"), wantCode: 451},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := mapSendError(tt.err, "127.0.0.1:1234")+ if tt.wantNil {+ if got != nil {+ t.Fatalf("expected nil error, got %v", got)+ }+ return+ }+ smtpErr, ok := got.(*smtp.SMTPError)+ if !ok {+ t.Fatalf("expected *smtp.SMTPError, got %T", got)+ }+ if smtpErr.Code != tt.wantCode {+ t.Fatalf("expected code %d, got %d", tt.wantCode, smtpErr.Code)+ }+ })+ }+}diff --git a/internal/services/smtprelay/credential.go b/internal/services/smtprelay/credential.gonew file mode 100644index 0000000..a20f6c3--- /dev/null+++ b/internal/services/smtprelay/credential.go@@ -0,0 +1,78 @@+/*+ * 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 smtprelay++import (+ "crypto/rand"+ "crypto/sha256"+ "encoding/hex"+ "fmt"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/storage/repositories"+)++// SMTPUsernamePrefix identifies a generated SMTP Relay username.+const SMTPUsernamePrefix = "smtp_"++type CredentialService struct {+ repo *repositories.SMTPCredentialRepository+}++func NewCredentialService(repo *repositories.SMTPCredentialRepository) *CredentialService {+ return &CredentialService{repo: repo}+}++func (s *CredentialService) GenerateCredential(userID, workspaceID uint, name string, allowedIPs []string) (username, password string, cred *models.SMTPCredential, err error) {+ userBytes := make([]byte, 8)+ if _, err = rand.Read(userBytes); err != nil {+ return "", "", nil, fmt.Errorf("failed to generate username: %w", err)+ }+ username = SMTPUsernamePrefix + hex.EncodeToString(userBytes)++ passBytes := make([]byte, 32)+ if _, err = rand.Read(passBytes); err != nil {+ return "", "", nil, fmt.Errorf("failed to generate password: %w", err)+ }+ password = hex.EncodeToString(passBytes)++ cred = &models.SMTPCredential{+ WorkspaceID: workspaceID,+ UserID: userID,+ Name: name,+ Username: username,+ PasswordHash: hashPassword(password),+ AllowedIPs: allowedIPs,+ }++ if err = s.repo.Create(cred); err != nil {+ return "", "", nil, err+ }++ return username, password, cred, nil+}++// VerifyPassword reports whether password matches cred's stored hash.+func VerifyPassword(cred *models.SMTPCredential, password string) bool {+ return cred.PasswordHash == hashPassword(password)+}++func hashPassword(password string) string {+ h := sha256.Sum256([]byte(password))+ return hex.EncodeToString(h[:])+}diff --git a/internal/services/smtprelay/credential_test.go b/internal/services/smtprelay/credential_test.gonew file mode 100644index 0000000..69a48c7--- /dev/null+++ b/internal/services/smtprelay/credential_test.go@@ -0,0 +1,51 @@+/*+ * 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 smtprelay++import (+ "testing"++ "github.com/goposta/posta/internal/models"+)++func TestHashPassword(t *testing.T) {+ h1 := hashPassword("correct-horse-battery-staple")+ h2 := hashPassword("correct-horse-battery-staple")+ if h1 != h2 {+ t.Errorf("hashPassword() is not deterministic: %q != %q", h1, h2)+ }+}++func TestHashPasswordDiffers(t *testing.T) {+ h1 := hashPassword("password-one")+ h2 := hashPassword("password-two")+ if h1 == h2 {+ t.Errorf("hashPassword() produced same hash for different passwords: %q", h1)+ }+}++func TestVerifyPassword(t *testing.T) {+ cred := &models.SMTPCredential{PasswordHash: hashPassword("s3cret-pass")}++ if !VerifyPassword(cred, "s3cret-pass") {+ t.Error("VerifyPassword() = false, want true for correct password")+ }+ if VerifyPassword(cred, "wrong-pass") {+ t.Error("VerifyPassword() = true, want false for incorrect password")+ }+}diff --git a/internal/services/smtprelay/smtp_server.go b/internal/services/smtprelay/smtp_server.gonew file mode 100644index 0000000..288c305--- /dev/null+++ b/internal/services/smtprelay/smtp_server.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 smtprelay++import (+ "fmt"+ "time"++ "github.com/emersion/go-smtp"+)++// SMTPConfig holds configuration for the built-in SMTP Relay listener.+type SMTPConfig struct {+ Host string+ Port int+ Hostname string+ MaxMessageSize int64+}++// AllowInsecureAuth is required here: it's what permits AUTH PLAIN without TLS.+func NewSMTPServer(backend *Backend, cfg SMTPConfig) (*smtp.Server, error) {+ srv := smtp.NewServer(backend)+ srv.Addr = fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)+ srv.Domain = cfg.Hostname+ srv.ReadTimeout = 30 * time.Second+ srv.WriteTimeout = 30 * time.Second+ srv.MaxMessageBytes = cfg.MaxMessageSize+ srv.MaxRecipients = 50+ srv.AllowInsecureAuth = true+ srv.EnableSMTPUTF8 = true+ return srv, nil+}diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.goindex 7429d19..9179896 100644--- a/internal/storage/migration/migration.go+++ b/internal/storage/migration/migration.go@@ -37,6 +37,7 @@ func Run(db *gorm.DB) error {&models.OAuthAccount{},&models.WorkspaceSSOConfig{},&models.APIKey{},+ &models.SMTPCredential{},&models.Email{},&models.InboundEmail{},&models.StyleSheet{},diff --git a/internal/storage/repositories/smtp_credential_repo.go b/internal/storage/repositories/smtp_credential_repo.gonew file mode 100644index 0000000..94474ad--- /dev/null+++ b/internal/storage/repositories/smtp_credential_repo.go@@ -0,0 +1,81 @@+/*+ * 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 (+ "time"++ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+)++type SMTPCredentialRepository struct {+ db *gorm.DB+}++func NewSMTPCredentialRepository(db *gorm.DB) *SMTPCredentialRepository {+ return &SMTPCredentialRepository{db: db}+}++func (r *SMTPCredentialRepository) Create(cred *models.SMTPCredential) error {+ return r.db.Create(cred).Error+}++func (r *SMTPCredentialRepository) FindByUsername(username string) (*models.SMTPCredential, error) {+ var cred models.SMTPCredential+ if err := r.db.Where("username = ?", username).First(&cred).Error; err != nil {+ return nil, err+ }+ return &cred, nil+}++func (r *SMTPCredentialRepository) FindByWorkspaceID(workspaceID uint, limit, offset int) ([]models.SMTPCredential, int64, error) {+ var creds []models.SMTPCredential+ var total int64++ r.db.Model(&models.SMTPCredential{}).Where("workspace_id = ?", workspaceID).Count(&total)++ if err := r.db.Where("workspace_id = ?", workspaceID).+ Order("created_at DESC").+ Limit(limit).Offset(offset).+ Find(&creds).Error; err != nil {+ return nil, 0, err+ }+ return creds, total, nil+}++func (r *SMTPCredentialRepository) FindByID(id uint) (*models.SMTPCredential, error) {+ var cred models.SMTPCredential+ if err := r.db.First(&cred, id).Error; err != nil {+ return nil, err+ }+ return &cred, nil+}++func (r *SMTPCredentialRepository) UpdateLastUsed(id uint) error {+ now := time.Now()+ return r.db.Model(&models.SMTPCredential{}).Where("id = ?", id).Update("last_used_at", now).Error+}++func (r *SMTPCredentialRepository) Revoke(id uint) error {+ return r.db.Model(&models.SMTPCredential{}).Where("id = ?", id).Update("revoked", true).Error+}++func (r *SMTPCredentialRepository) Delete(id uint) error {+ return r.db.Delete(&models.SMTPCredential{}, id).Error+}diff --git a/web/src/api/smtpRelay.ts b/web/src/api/smtpRelay.tsnew file mode 100644index 0000000..dcb9f31--- /dev/null+++ b/web/src/api/smtpRelay.ts@@ -0,0 +1,19 @@+import api from './client'+import type { ApiResponse, PaginatedResponse, SMTPCredential, SMTPCredentialCreateResponse } from './types'++export const smtpRelayApi = {+ list(page = 0, size = 20) {+ return api.get<PaginatedResponse<SMTPCredential>>('/workspaces/current/smtp-credentials', { params: { page, size } })+ },+ create(name: string, allowedIPs?: string[]) {+ const body: Record<string, any> = { name }+ if (allowedIPs && allowedIPs.length > 0) body.allowed_ips = allowedIPs+ return api.post<ApiResponse<SMTPCredentialCreateResponse>>('/workspaces/current/smtp-credentials', body)+ },+ revoke(id: number) {+ return api.post(`/workspaces/current/smtp-credentials/${id}/revoke`)+ },+ delete(id: number) {+ return api.delete(`/workspaces/current/smtp-credentials/${id}`)+ },+}diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 39710ee..b97c1d0 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -145,6 +145,29 @@ export interface ApiKeyCreateResponse {message: string}+export interface SMTPCredential {+ id: number+ workspace_id: number+ user_id: number+ name: string+ username: string+ revoked: boolean+ allowed_ips: string[] | null+ created_at: string+ last_used_at: string | null+}++export interface SMTPCredentialCreateResponse {+ id: number+ name: string+ username: string+ password: string+ host: string+ port: number+ created_at: string+ message: string+}+export interface ActorRef {id: numbername: stringdiff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex 57b3ce3..ab64bba 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -161,6 +161,7 @@ const navSections: NavSection[] = [defaultOpen: true,items: [{ name: 'API Keys', path: '/api-keys', icon: 'key' },+ { name: 'SMTP Relay', path: '/smtp-relay', icon: 'server' },{ name: 'Webhooks', path: '/webhooks', icon: 'link' },{ name: 'Webhook Deliveries', path: '/webhook-deliveries', icon: 'activity' },{ name: 'API Reference', path: '/docs', icon: 'book-open', external: true, requiresOpenapiDocs: true },diff --git a/web/src/router/index.ts b/web/src/router/index.tsindex 1faea4b..b3d510d 100644--- a/web/src/router/index.ts+++ b/web/src/router/index.ts@@ -56,6 +56,7 @@ const routes = [{ path: '', name: 'dashboard', component: () => import('../views/dashboard/Dashboard.vue'), meta: { title: 'Dashboard' } },{ path: 'api-keys', name: 'api-keys', component: () => import('../views/apikeys/ApiKeys.vue'), meta: { title: 'API Keys' } },{ path: 'api-keys/:id', name: 'api-key-detail', component: () => import('../views/apikeys/ApiKeyDetail.vue'), meta: { title: 'API Key' } },+ { path: 'smtp-relay', name: 'smtp-relay', component: () => import('../views/smtp-relay/SmtpCredentials.vue'), meta: { title: 'SMTP Relay' } },{ path: 'emails', name: 'emails', component: () => import('../views/emails/Emails.vue'), meta: { title: 'Emails' } },{ path: 'emails/:id', name: 'email-detail', component: () => import('../views/emails/EmailDetail.vue'), meta: { title: 'Email' } },{ path: 'inbound-emails', name: 'inbound-emails', component: () => import('../views/inbound/InboundEmails.vue'), meta: { title: 'Inbound Emails' } },diff --git a/web/src/views/smtp-relay/SmtpCredentials.vue b/web/src/views/smtp-relay/SmtpCredentials.vuenew file mode 100644index 0000000..fa7467f--- /dev/null+++ b/web/src/views/smtp-relay/SmtpCredentials.vue@@ -0,0 +1,326 @@+<script setup lang="ts">+import { ref, onMounted } from 'vue'+import { smtpRelayApi } from '../../api/smtpRelay'+import type { SMTPCredential, SMTPCredentialCreateResponse } from '../../api/types'+import { infoApi, type AppInfo } from '../../api/info'+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 notify = useNotificationStore()+const wsStore = useWorkspaceStore()+const { confirm } = useConfirm()++const credentials = ref<SMTPCredential[]>([])+const loading = ref(true)+const featureDisabled = ref(false)+const appInfo = ref<AppInfo | null>(null)++const showCreateModal = ref(false)+const newCredentialName = ref('')+const newCredentialIPs = ref('')+const creating = ref(false)++const createdCredential = ref<SMTPCredentialCreateResponse | null>(null)+const showCredentialModal = ref(false)+const copied = ref(false)++const { pageable, goToPage } = usePagination(async (page) => {+ loading.value = true+ try {+ const res = await smtpRelayApi.list(page, pageable.value.size)+ credentials.value = res.data.data+ pageable.value = res.data.pageable+ featureDisabled.value = false+ } catch (e: any) {+ if (e?.response?.status === 404) {+ featureDisabled.value = true+ } else {+ console.error('Failed to load SMTP credentials', e)+ }+ } finally {+ loading.value = false+ }+})++async function createCredential() {+ if (!newCredentialName.value.trim()) return+ creating.value = true+ try {+ const allowedIPs = newCredentialIPs.value+ .split(/[,\n]/)+ .map(ip => ip.trim())+ .filter(ip => ip.length > 0)+ const res = await smtpRelayApi.create(+ newCredentialName.value.trim(),+ allowedIPs.length > 0 ? allowedIPs : undefined,+ )+ createdCredential.value = res.data.data+ showCreateModal.value = false+ newCredentialName.value = ''+ newCredentialIPs.value = ''+ showCredentialModal.value = true+ notify.success('SMTP credential created')+ await goToPage(pageable.value.current_page)+ } catch {+ notify.error('Failed to create SMTP credential')+ } finally {+ creating.value = false+ }+}++async function revokeCredential(cred: SMTPCredential) {+ const confirmed = await confirm({+ title: 'Revoke SMTP Credential',+ message: `Are you sure you want to revoke "${cred.name}"? This credential will immediately stop working and cannot be reactivated.`,+ confirmText: 'Revoke',+ variant: 'danger',+ })+ if (!confirmed) return+ try {+ await smtpRelayApi.revoke(cred.id)+ notify.success('SMTP credential revoked')+ await goToPage(pageable.value.current_page)+ } catch {+ notify.error('Failed to revoke SMTP credential')+ }+}++async function deleteCredential(cred: SMTPCredential) {+ const confirmed = await confirm({+ title: 'Delete SMTP Credential',+ message: `Are you sure you want to permanently delete "${cred.name}"? This action cannot be undone.`,+ confirmText: 'Delete',+ variant: 'danger',+ })+ if (!confirmed) return+ try {+ await smtpRelayApi.delete(cred.id)+ notify.success('SMTP credential deleted')+ await goToPage(pageable.value.current_page)+ } catch {+ notify.error('Failed to delete SMTP credential')+ }+}++function copyCredential() {+ if (!createdCredential.value) return+ const c = createdCredential.value+ const text = `Host: ${c.host}\nPort: ${c.port}\nUsername: ${c.username}\nPassword: ${c.password}`+ navigator.clipboard.writeText(text)+ copied.value = true+ setTimeout(() => (copied.value = false), 2000)+}++function closeCredentialModal() {+ showCredentialModal.value = false+ createdCredential.value = null+ copied.value = false+}++function credentialStatus(cred: SMTPCredential): { label: string; class: string } {+ if (cred.revoked) return { label: 'Revoked', class: 'badge-danger' }+ return { label: 'Active', class: 'badge-success' }+}++function formatDate(dateStr: string): string {+ return new Date(dateStr).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })+}++const { watchClickStart, confirmClickEnd } = useModalSafeClose(() => {+ showCreateModal.value = false+})++onMounted(() => {+ infoApi.get().then((res) => { appInfo.value = res.data.data }).catch(() => {})+})+</script>++<template>+ <div>+ <div class="page-header">+ <h1>SMTP Relay</h1>+ <button v-if="wsStore.canEdit && !featureDisabled" class="btn btn-primary" @click="showCreateModal = true">Create Credential</button>+ </div>++ <div v-if="appInfo?.openapi_docs && !featureDisabled" class="card api-docs-callout">+ <div class="api-docs-text">+ <strong>Developer resources</strong>+ <span>Authenticate an existing SMTP client with these credentials to relay mail through Posta's outbound pipeline.</span>+ </div>+ <div class="api-docs-links">+ <a class="btn btn-secondary btn-sm" href="/docs" target="_blank" rel="noopener noreferrer">API Reference</a>+ </div>+ </div>++ <div v-if="loading" class="loading-page">+ <div class="spinner"></div>+ </div>++ <div v-else-if="featureDisabled" class="card">+ <div class="empty-state">+ <h3>SMTP Relay is disabled</h3>+ <p>+ Ask your administrator to enable it by setting+ <code>POSTA_SMTP_RELAY_ENABLED=true</code> and configuring the SMTP listener.+ </p>+ </div>+ </div>++ <div v-else class="card">+ <div v-if="credentials.length === 0" class="empty-state">+ <h3>No SMTP Credentials</h3>+ <p>Create a credential to let an SMTP client relay mail through Posta.</p>+ </div>++ <template v-else>+ <div class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th>Name</th>+ <th>Username</th>+ <th>Created</th>+ <th>Last Used</th>+ <th>IP Allowlist</th>+ <th>Status</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="cred in credentials" :key="cred.id">+ <td>{{ cred.name }}</td>+ <td><code>{{ cred.username }}</code></td>+ <td>{{ formatDate(cred.created_at) }}</td>+ <td>{{ cred.last_used_at ? formatDate(cred.last_used_at) : 'Never' }}</td>+ <td>+ <template v-if="cred.allowed_ips && cred.allowed_ips.length > 0">+ <code v-for="(ip, i) in cred.allowed_ips.slice(0, 2)" :key="i" style="margin-right: 4px; font-size: 12px">{{ ip }}</code>+ <span v-if="cred.allowed_ips.length > 2" style="font-size: 12px; color: var(--text-muted)">+{{ cred.allowed_ips.length - 2 }} more</span>+ </template>+ <span v-else style="color: var(--text-muted)">Any</span>+ </td>+ <td>+ <span class="badge" :class="credentialStatus(cred).class">{{ credentialStatus(cred).label }}</span>+ </td>+ <td>+ <div style="display: flex; gap: 6px">+ <button+ v-if="wsStore.canEdit && !cred.revoked"+ class="btn btn-warning btn-sm"+ @click="revokeCredential(cred)"+ >+ Revoke+ </button>+ <button+ v-if="wsStore.canEdit && cred.revoked"+ class="btn btn-danger btn-sm"+ @click="deleteCredential(cred)"+ >+ Delete+ </button>+ </div>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ <Pagination :pageable="pageable" @page="goToPage" />+ </template>+ </div>++ <!-- Create Credential Modal -->+ <div v-if="showCreateModal" class="modal-overlay" @mousedown="watchClickStart" @mouseup="confirmClickEnd">+ <div class="modal" @mousedown.stop @mouseup.stop>+ <div class="modal-header">+ <h3>Create SMTP Credential</h3>+ </div>+ <div class="modal-body">+ <div class="form-group">+ <label class="form-label">Name</label>+ <input+ v-model="newCredentialName"+ class="form-input"+ placeholder="e.g. Legacy App, Staging"+ @keyup.enter="createCredential"+ />+ </div>+ <div class="form-group">+ <label class="form-label">Allowed IPs <span style="font-weight: 400; color: var(--text-muted)">(optional)</span></label>+ <textarea+ v-model="newCredentialIPs"+ class="form-input"+ rows="3"+ placeholder="Comma or newline separated, e.g. 192.168.1.1 10.0.0.0/24"+ ></textarea>+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block">+ Restrict this credential to specific IP addresses. Leave empty to allow all.+ </small>+ </div>+ </div>+ <div class="modal-footer">+ <button class="btn btn-secondary" @click="showCreateModal = false">Cancel</button>+ <button class="btn btn-primary" :disabled="creating || !newCredentialName.trim()" @click="createCredential">+ {{ creating ? 'Creating...' : 'Create' }}+ </button>+ </div>+ </div>+ </div>++ <!-- Show Credential Modal -->+ <div v-if="showCredentialModal" class="modal-overlay">+ <div class="modal">+ <div class="modal-header">+ <h3>SMTP Credential Created</h3>+ </div>+ <div class="modal-body">+ <p class="text-sm" style="color: var(--danger-600); font-weight: 500; margin-bottom: 12px;">+ {{ createdCredential?.message || "Save this password securely. It will not be shown again." }}+ </p>+ <div class="form-group">+ <label class="form-label">Host</label>+ <div class="code-block">{{ createdCredential?.host }}</div>+ </div>+ <div class="form-group">+ <label class="form-label">Port</label>+ <div class="code-block">{{ createdCredential?.port }}</div>+ </div>+ <div class="form-group">+ <label class="form-label">Username</label>+ <div class="code-block">{{ createdCredential?.username }}</div>+ </div>+ <div class="form-group">+ <label class="form-label">Password</label>+ <div class="code-block">{{ createdCredential?.password }}</div>+ </div>+ <button class="btn btn-secondary btn-sm mt-4" @click="copyCredential">+ {{ copied ? 'Copied!' : 'Copy Credentials' }}+ </button>+ </div>+ <div class="modal-footer">+ <button class="btn btn-primary" @click="closeCredentialModal">Done</button>+ </div>+ </div>+ </div>+ </div>+</template>++<style scoped>+.api-docs-callout {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ flex-wrap: wrap;+ padding: 16px 20px;+ margin-bottom: 20px;+}+.api-docs-text { display: flex; flex-direction: column; gap: 2px; }+.api-docs-text strong { font-size: 14px; color: var(--text-primary); }+.api-docs-text span { font-size: 13px; color: var(--text-secondary); }+.api-docs-links { display: flex; gap: 8px; flex-shrink: 0; }+.api-docs-links .btn { text-decoration: none; }+</style>