Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(email): add SMTP relay as alternative to Resend for self-hosted deployments (#1877)

apollion6935e9a7f0f637
diff --git a/.env.example b/.env.example
index 0a9384dee1..e8357a83d3 100644
--- a/.env.example
+++ b/.env.example
@@ -48,11 +48,25 @@ MULTICA_IMAGE_TAG=latest
MULTICA_BACKEND_IMAGE=ghcr.io/multica-ai/multica-backend
MULTICA_WEB_IMAGE=ghcr.io/multica-ai/multica-web
-# Email (Resend)
-# For local/dev use, leave RESEND_API_KEY empty — generated codes print to stdout.
-# For production, set your Resend API key and change RESEND_FROM_EMAIL to a domain verified in your Resend account.
+# Email
+# Two delivery options - only one needs to be configured:
+#
+# Option A: Resend (SaaS, recommended for cloud deployments)
+# Set RESEND_API_KEY to a key from resend.com and verify your sending domain there.
+# For local/dev use, leave RESEND_API_KEY empty - codes print to stdout and
+# master code 888888 works (only when APP_ENV != "production").
RESEND_API_KEY=
+#
+# Option B: SMTP relay (for self-hosted / on-premise deployments)
+# Takes priority over Resend when SMTP_HOST is set.
+# Supports unauthenticated relay (leave SMTP_USERNAME empty) and authenticated SMTP.
+# Set SMTP_TLS_INSECURE=true only for private CA or self-signed certificates.
+SMTP_HOST=
+SMTP_PORT=25
+SMTP_USERNAME=
+SMTP_PASSWORD=
+SMTP_TLS_INSECURE=false
# Google OAuth
# The web login page reads GOOGLE_CLIENT_ID from /api/config at runtime, so
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index 36f4aee1ef..b636d67798 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -25,14 +25,30 @@ These have sensible defaults and only need to be set when tuning a large or cons
### Email (Required for Authentication)
-Multica uses email-based magic link authentication via [Resend](https://resend.com).
+Multica supports two email backends. `SMTP_HOST` takes priority when set; otherwise `RESEND_API_KEY` is used. In local development with neither configured, verification codes are printed to the server log and the master code `888888` is active (only when `APP_ENV=development`).
+
+#### Option A: Resend (recommended for cloud deployments)
| Variable | Description |
|----------|-------------|
| `RESEND_API_KEY` | Your Resend API key |
| `RESEND_FROM_EMAIL` | Sender email address (default: `[email protected]`) |
-> **Note:** If Resend is not configured, generated verification codes are printed to backend logs. A fixed local testing code is disabled by default; to opt in on a private test instance, set `APP_ENV=development` and `MULTICA_DEV_VERIFICATION_CODE` to a 6-digit value. It is ignored when `APP_ENV=production`.
+#### Option B: SMTP relay (for self-hosted / on-premise deployments)
+
+Use this option when your deployment cannot reach the public internet or you already have an internal mail relay (e.g. Exchange, Postfix, SendGrid on-prem).
+
+| Variable | Description | Default |
+|----------|-------------|----------|
+| `SMTP_HOST` | SMTP relay hostname (setting this activates SMTP mode) | - |
+| `SMTP_PORT` | SMTP port | `25` |
+| `SMTP_USERNAME` | SMTP username (leave empty for unauthenticated relay) | - |
+| `SMTP_PASSWORD` | SMTP password | - |
+| `SMTP_TLS_INSECURE` | Set `true` to skip TLS certificate verification (self-signed / private CA certs) | `false` |
+
+STARTTLS is used automatically when advertised by the server. Port 465 (SMTPS / implicit TLS) is not currently supported - use ports 25 or 587 with STARTTLS.
+
+> **Note:** If Resend is not configured, generated verification codes are printed to backend logs. The dev master verification code `888888` is gated by `APP_ENV != "production"`. The Docker self-host stack defaults to `APP_ENV=production` (so `888888` is disabled). For local development without email configured, set `APP_ENV=development` in your `.env` to enable `888888` - never do this on a public instance.
### Google OAuth (Optional)
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 3c5dbd99f7..91fd0394e9 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -46,6 +46,11 @@ services:
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
RESEND_API_KEY: ${RESEND_API_KEY:-}
RESEND_FROM_EMAIL: ${RESEND_FROM_EMAIL:[email protected]}
+ SMTP_HOST: ${SMTP_HOST:-}
+ SMTP_PORT: ${SMTP_PORT:-25}
+ SMTP_USERNAME: ${SMTP_USERNAME:-}
+ SMTP_PASSWORD: ${SMTP_PASSWORD:-}
+ SMTP_TLS_INSECURE: ${SMTP_TLS_INSECURE:-false}
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
GOOGLE_REDIRECT_URI: ${GOOGLE_REDIRECT_URI:-http://localhost:3000/auth/callback}
diff --git a/server/internal/service/email.go b/server/internal/service/email.go
index ab55273711..6b927fdff7 100644
--- a/server/internal/service/email.go
+++ b/server/internal/service/email.go
@@ -1,10 +1,16 @@
package service
import (
+ "crypto/tls"
"fmt"
"html"
+ "mime"
+ "mime/quotedprintable"
+ "net"
+ "net/smtp"
"os"
"strings"
+ "time"
"unicode"
"unicode/utf8"
@@ -17,51 +23,173 @@ import (
const maxSubjectFieldRunes = 60
type EmailService struct {
- client *resend.Client
- fromEmail string
+ client *resend.Client
+ fromEmail string
+ smtpHost string
+ smtpPort string
+ smtpUsername string
+ smtpPassword string
+ smtpTLSInsecure bool
}
func NewEmailService() *EmailService {
apiKey := os.Getenv("RESEND_API_KEY")
- from := os.Getenv("RESEND_FROM_EMAIL")
+ from := strings.TrimSpace(os.Getenv("RESEND_FROM_EMAIL"))
if from == "" {
}
+ smtpHost := strings.TrimSpace(os.Getenv("SMTP_HOST"))
+ smtpPort := strings.TrimSpace(os.Getenv("SMTP_PORT"))
+ if smtpPort == "" {
+ smtpPort = "25"
+ }
+ smtpUsername := os.Getenv("SMTP_USERNAME")
+ smtpPassword := os.Getenv("SMTP_PASSWORD")
+ smtpTLSInsecure := os.Getenv("SMTP_TLS_INSECURE") == "true"
+
var client *resend.Client
if apiKey != "" {
client = resend.NewClient(apiKey)
}
+ switch {
+ case smtpHost != "":
+ fmt.Printf("EmailService: SMTP relay %s:%s from=%s\n", smtpHost, smtpPort, from)
+ case client != nil:
+ fmt.Printf("EmailService: Resend API from=%s\n", from)
+ default:
+ fmt.Println("EmailService: DEV mode — codes printed to stdout, master code 888888 active")
+ }
+
return &EmailService{
- client: client,
- fromEmail: from,
+ client: client,
+ fromEmail: from,
+ smtpHost: smtpHost,
+ smtpPort: smtpPort,
+ smtpUsername: smtpUsername,
+ smtpPassword: smtpPassword,
+ smtpTLSInsecure: smtpTLSInsecure,
+ }
+}
+
+// sendSMTP delivers an HTML email via an SMTP server.
+// Supports unauthenticated relay (SMTP_USERNAME empty) and authenticated SMTP.
+// Upgrades to STARTTLS when advertised by the server.
+// Set SMTP_TLS_INSECURE=true for self-signed or private CA certificates.
+func (s *EmailService) sendSMTP(to, subject, htmlBody string) error {
+ addr := net.JoinHostPort(s.smtpHost, s.smtpPort)
+
+ // Bounded dial + whole-session deadline: prevents a blackholed SMTP server
+ // from hanging the auth handler (or a background goroutine) indefinitely.
+ conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
+ if err != nil {
+ return fmt.Errorf("smtp dial %s: %w", addr, err)
+ }
+ if err = conn.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
+ conn.Close()
+ return fmt.Errorf("smtp set deadline: %w", err)
+ }
+
+ c, err := smtp.NewClient(conn, s.smtpHost)
+ if err != nil {
+ conn.Close()
+ return fmt.Errorf("smtp client: %w", err)
+ }
+ defer c.Close()
+
+ // STARTTLS if advertised — refreshes the extension list for 8BITMIME check below.
+ if ok, _ := c.Extension("STARTTLS"); ok {
+ tlsCfg := &tls.Config{
+ ServerName: s.smtpHost,
+ InsecureSkipVerify: s.smtpTLSInsecure, //nolint:gosec // opt-in via SMTP_TLS_INSECURE=true
+ }
+ if err = c.StartTLS(tlsCfg); err != nil {
+ return fmt.Errorf("smtp starttls: %w", err)
+ }
+ }
+
+ if s.smtpUsername != "" {
+ auth := smtp.PlainAuth("", s.smtpUsername, s.smtpPassword, s.smtpHost)
+ if err = c.Auth(auth); err != nil {
+ return fmt.Errorf("smtp auth: %w", err)
+ }
+ }
+
+ // Probe 8BITMIME after (possible) STARTTLS so the extension list is current.
+ // Use quoted-printable for relays that don't advertise 8BITMIME — safer for
+ // non-ASCII workspace/inviter names crossing strict or older SMTP hops.
+ has8Bit, _ := c.Extension("8BITMIME")
+ encodedSubject := mime.QEncoding.Encode("utf-8", subject)
+ msgID := fmt.Sprintf("<%d@%s>", time.Now().UnixNano(), s.smtpHost)
+
+ var bodyBytes []byte
+ var cte string
+ if has8Bit {
+ bodyBytes = []byte(htmlBody)
+ cte = "8bit"
+ } else {
+ var buf strings.Builder
+ qpw := quotedprintable.NewWriter(&buf)
+ _, _ = qpw.Write([]byte(htmlBody))
+ _ = qpw.Close()
+ bodyBytes = []byte(buf.String())
+ cte = "quoted-printable"
+ }
+
+ if err = c.Mail(s.fromEmail); err != nil {
+ return fmt.Errorf("smtp MAIL FROM: %w", err)
+ }
+ if err = c.Rcpt(to); err != nil {
+ return fmt.Errorf("smtp RCPT TO <%s>: %w", to, err)
+ }
+ w, err := c.Data()
+ if err != nil {
+ return fmt.Errorf("smtp DATA: %w", err)
+ }
+ headers := "From: " + s.fromEmail + "\r\n" +
+ "To: " + to + "\r\n" +
+ "Subject: " + encodedSubject + "\r\n" +
+ "Date: " + time.Now().UTC().Format(time.RFC1123Z) + "\r\n" +
+ "Message-ID: " + msgID + "\r\n" +
+ "MIME-Version: 1.0\r\n" +
+ "Content-Type: text/html; charset=UTF-8\r\n" +
+ "Content-Transfer-Encoding: " + cte + "\r\n" +
+ "\r\n"
+ if _, err = fmt.Fprintf(w, "%s%s", headers, bodyBytes); err != nil {
+ return fmt.Errorf("smtp write body: %w", err)
}
+ if err = w.Close(); err != nil {
+ return fmt.Errorf("smtp end data: %w", err)
+ }
+ return c.Quit()
}
// SendVerificationCode sends a one-time login code. The code is server-generated
// (6-digit numeric) so no user-controlled text reaches the email body here.
-// If that ever changes, escape the user-controlled fields the same way
-// SendInvitationEmail does.
+// Delivery priority: SMTP relay → Resend API → DEV stdout.
func (s *EmailService) SendVerificationCode(to, code string) error {
+ body := fmt.Sprintf(
+ `<div style="font-family: sans-serif; max-width: 400px; margin: 0 auto;">
+ <h2>Your verification code</h2>
+ <p style="font-size: 32px; font-weight: bold; letter-spacing: 8px; margin: 24px 0;">%s</p>
+ <p>This code expires in 10 minutes.</p>
+ <p style="color: #666; font-size: 14px;">If you didn't request this code, you can safely ignore this email.</p>
+ </div>`, code)
+
+ if s.smtpHost != "" {
+ return s.sendSMTP(to, "Your Multica verification code", body)
+ }
if s.client == nil {
fmt.Printf("[DEV] Verification code for %s: %s\n", to, code)
return nil
}
-
params := &resend.SendEmailRequest{
From: s.fromEmail,
To: []string{to},
Subject: "Your Multica verification code",
- Html: fmt.Sprintf(
- `<div style="font-family: sans-serif; max-width: 400px; margin: 0 auto;">
- <h2>Your verification code</h2>
- <p style="font-size: 32px; font-weight: bold; letter-spacing: 8px; margin: 24px 0;">%s</p>
- <p>This code expires in 10 minutes.</p>
- <p style="color: #666; font-size: 14px;">If you didn't request this code, you can safely ignore this email.</p>
- </div>`, code),
+ Html: body,
}
-
_, err := s.client.Emails.Send(params)
return err
}
@@ -75,19 +203,22 @@ func (s *EmailService) SendInvitationEmail(to, inviterName, workspaceName, invit
}
inviteURL := fmt.Sprintf("%s/invite/%s", appURL, invitationID)
+ if s.smtpHost != "" {
+ params := buildInvitationParams(s.fromEmail, to, inviterName, workspaceName, inviteURL)
+ return s.sendSMTP(to, params.Subject, params.Html)
+ }
if s.client == nil {
fmt.Printf("[DEV] Invitation email to %s: %s invited you to %s — %s\n", to, inviterName, workspaceName, inviteURL)
return nil
}
-
params := buildInvitationParams(s.fromEmail, to, inviterName, workspaceName, inviteURL)
_, err := s.client.Emails.Send(params)
return err
}
-// buildInvitationParams assembles the Resend request for an invitation email.
+// buildInvitationParams assembles the email request for an invitation.
// Separated from SendInvitationEmail so the sanitization behavior is unit-testable
-// without needing to mock the Resend SDK.
+// without needing to mock the Resend SDK or an SMTP server.
func buildInvitationParams(from, to, inviterName, workspaceName, inviteURL string) *resend.SendEmailRequest {
safeWorkspace := html.EscapeString(workspaceName)
safeInviter := html.EscapeString(inviterName)