High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
Add per-domain SMTP routing (#2953)
Phil Dibowitz41a29fb244e7
diff --git a/cmd/settings.go b/cmd/settings.goindex d1441a61..ced9a33d 100644--- a/cmd/settings.go+++ b/cmd/settings.go@@ -151,6 +151,23 @@ func (a *App) UpdateSettings(c echo.Context) error {return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("settings.errorNoSMTP"))}+ // Normalize `from_addresses``. Values are either an e-mail address+ // or an FQDN. Duplicate domains across server blocks are allowed+ // (they get round-robin'd while sending).+ for i, s := range set.SMTP {+ if !s.Enabled {+ continue+ }++ addrs := make([]string, 0, len(s.FromAddresses))+ for _, addr := range s.FromAddresses {+ if k := email.NormalizeAddr(addr); k != "" {+ addrs = append(addrs, k)+ }+ }+ set.SMTP[i].FromAddresses = addrs+ }+// Always remove the trailing slash from the app root URL.set.AppRootURL = strings.TrimRight(set.AppRootURL, "/")diff --git a/frontend/src/views/settings/smtp.vue b/frontend/src/views/settings/smtp.vueindex 3aaf1f80..b3edc37f 100644--- a/frontend/src/views/settings/smtp.vue+++ b/frontend/src/views/settings/smtp.vue@@ -161,6 +161,13 @@<b-input v-model="item.name" name="name" placeholder="email-primary" :maxlength="100" /></b-field></div>+ <div class="column is-6">+ <b-field :label="$t('settings.smtp.fromAddresses')" label-position="on-border"+ :message="$t('settings.smtp.fromAddressesHelp')">+ <b-taginput v-model="item.from_addresses" name="from_addresses" ellipsis icon="tag-outline"+ :before-adding="validateFromAddress" placeholder="[email protected], anothersite.com" />+ </b-field>+ </div></div><div class="columns">@@ -288,6 +295,7 @@ export default Vue.extend({username: '',password: '',email_headers: [],+ from_addresses: [],max_conns: 10,max_msg_retries: 2,msg_retry_delay: '0s',@@ -363,6 +371,11 @@ export default Vue.extend({return true;},+ validateFromAddress(v) {+ // Accept an e-mail address ([email protected]) or a domain (example.com).+ return /^[^\s@]+(\.[^\s@]+)+$|^[^\s@]+@[^\s@]+(\.[^\s@]+)+$/.test(v);+ },+fillSettings(n, key) {this.data.smtp.splice(n, 1, {...this.data.smtp[n],diff --git a/i18n/en.json b/i18n/en.jsonindex 40e0146a..ffe3135b 100644--- a/i18n/en.json+++ b/i18n/en.json@@ -563,6 +563,8 @@"settings.smtp.customHeaders": "Custom headers","settings.smtp.customHeadersHelp": "Optional array of e-mail headers to include in all messages sent from this server. eg: [{\"X-Custom\": \"value\"}, {\"X-Custom2\": \"value\"}]","settings.smtp.enabled": "Enabled",+ "settings.smtp.fromAddresses": "From addresses / domains",+ "settings.smtp.fromAddressesHelp": "Optional list of e-mail addresses ([email protected]) or domains (example.com) to route through this SMTP server. If multiple servers specify the same entry, they are used round robin.","settings.smtp.heloHost": "HELO hostname","settings.smtp.heloHostHelp": "Optional. Some SMTP servers require a FQDN in the hostname. By default, HELLOs go with `localhost`. Set this if a custom hostname should be used.","settings.smtp.name": "SMTP",diff --git a/internal/messenger/email/email.go b/internal/messenger/email/email.goindex dbbcbd2d..9b3f6398 100644--- a/internal/messenger/email/email.go+++ b/internal/messenger/email/email.go@@ -33,6 +33,7 @@ type Server struct {TLSType string `json:"tls_type"`TLSSkipVerify bool `json:"tls_skip_verify"`EmailHeaders map[string]string `json:"email_headers"`+ FromAddresses []string `json:"from_addresses"`// Rest of the options are embedded directly from the smtppool lib.// The JSON tag is for config unmarshal to work.@@ -44,8 +45,17 @@ type Server struct {// Emailer is the SMTP e-mail messenger.type Emailer struct {- servers []*Server- name string+ name string++ // pools holds groups of SMTP servers indexed by a key ('from'-address+ // or a domain set per SMTPs server). An empty key holds all servers+ // and is the fallback round-robin when there's no match (old behaviour).+ pools map[string][]*Server+}++// NormalizeAddr normalizes an e-mail address (strip spaces, lowercase).+func NormalizeAddr(s string) string {+ return strings.ToLower(strings.TrimSpace(s))}// New returns an SMTP e-mail Messenger backend with the given SMTP servers.@@ -53,8 +63,8 @@ type Emailer struct {// that are used as a round-robin pool, or a single server.func New(name string, servers ...Server) (*Emailer, error) {e := &Emailer{- servers: make([]*Server, 0, len(servers)),- name: name,+ name: name,+ pools: make(map[string][]*Server),}for _, srv := range servers {@@ -99,7 +109,15 @@ func New(name string, servers ...Server) (*Emailer, error) {}s.pool = pool- e.servers = append(e.servers, &s)++ // Add to the global list (empty key) and to each from-address+ // bucket. Duplicate keys across servers are fine and get round-robin'd.+ e.pools[""] = append(e.pools[""], &s)+ for _, addr := range s.FromAddresses {+ if key := NormalizeAddr(addr); key != "" {+ e.pools[key] = append(e.pools[key], &s)+ }+ }}return e, nil@@ -112,17 +130,15 @@ func (e *Emailer) Name() string {// Push pushes a message to the server.func (e *Emailer) Push(m models.Message) error {- // If there are more than one SMTP servers, send to a random- // one from the list.- var (- ln = len(e.servers)- srv *Server- )- if ln > 1 {- srv = e.servers[rand.Intn(ln)]- } else {- srv = e.servers[0]+ // Pick the from-address-routed pool if there is one, else default+ // to the full pool (empty key) for roundrobin.+ pool := e.pools[""]+ if len(e.pools) > 1 {+ if srvs := e.getPool(m.From); srvs != nil {+ pool = srvs+ }}+ srv := pool[rand.Intn(len(pool))]// Are there attachments?var files []smtppool.Attachment@@ -213,8 +229,28 @@ func (e *Emailer) Flush() error {// Close closes the SMTP pools.func (e *Emailer) Close() error {- for _, s := range e.servers {+ for _, s := range e.pools[""] {s.pool.Close()}return nil}++// getPool returns the pool of servers configured to handle the given From+// header, matched by full e-mail and then by domain.+// Returns nil if no mapping matches.+func (e *Emailer) getPool(from string) []*Server {+ addr := utils.ParseEmailAddress(from)+ if addr == "" {+ return nil+ }++ if srvs, ok := e.pools[addr]; ok {+ return srvs+ }++ if _, after, ok := strings.Cut(addr, "@"); ok {+ return e.pools[after]+ }++ return nil+}diff --git a/internal/subimporter/importer.go b/internal/subimporter/importer.goindex f318bc39..88059eba 100644--- a/internal/subimporter/importer.go+++ b/internal/subimporter/importer.go@@ -16,7 +16,6 @@ import ("fmt""io""log"- "net/mail""os""regexp""strings"@@ -24,6 +23,7 @@ import ("github.com/gofrs/uuid/v5""github.com/knadh/listmonk/internal/i18n"+ "github.com/knadh/listmonk/internal/utils""github.com/knadh/listmonk/models""github.com/lib/pq""golang.org/x/text/cases"@@ -601,25 +601,21 @@ func (im *Importer) Stop() {}}-// SanitizeEmail validates and sanitizes an e-mail string and returns the lowercased,-// e-mail component of an e-mail string.+// SanitizeEmail validates and sanitizes an e-mail string and returns the+// canonical (lowercased, trimmed) address. Domain allowlist/blocklist rules+// are enforced on top of the bare-address validation in utils.SanitizeEmail.func (im *Importer) SanitizeEmail(email string) (string, error) {- email = strings.ToLower(strings.TrimSpace(email))-- // Since `mail.ParseAddress` parses an email address which can also contain optional name component- // here we check if incoming email string is same as the parsed email.Address. So this eliminates- // any valid email address with name and also valid address with empty name like `<[email protected]>`.- em, err := mail.ParseAddress(email)- if err != nil || em.Address != email {+ addr, err := utils.SanitizeEmail(email)+ if err != nil {return "", errors.New(im.i18n.T("subscribers.invalidEmail"))}// Check if the e-mail's domain is blocklisted. The e-mail domain and blocklist config// are always lowercase.if im.hasAllowlist || im.hasBlocklist {- d := strings.Split(em.Address, "@")+ d := strings.Split(addr, "@")if len(d) != 2 {- return em.Address, nil+ return addr, nil}domain := d[1]@@ -636,7 +632,7 @@ func (im *Importer) SanitizeEmail(email string) (string, error) {}}- return em.Address, nil+ return addr, nil}// ValidateFields validates incoming subscriber field values and returns sanitized fields.diff --git a/internal/utils/utils.go b/internal/utils/utils.goindex 60c1f9ee..44aa5175 100644--- a/internal/utils/utils.go+++ b/internal/utils/utils.go@@ -2,23 +2,48 @@ package utilsimport ("crypto/rand"+ "errors""net/mail""net/url""path""strings")-// ValidateEmail validates whether the given string is a correctly formed e-mail address.-func ValidateEmail(email string) bool {- // Since `mail.ParseAddress` parses an email address which can also contain an optional name component,- // here we check if incoming email string is same as the parsed email.Address. So this eliminates- // any valid email address with name and also valid address with empty name like `<[email protected]>`.- em, err := mail.ParseAddress(email)- if err != nil || em.Address != email {- return false+// ErrInvalidEmail is returned by SanitizeEmail for malformed input.+var ErrInvalidEmail = errors.New("invalid e-mail address")++// ValidateEmail reports whether s is a correctly formed bare e-mail address+// (no display name component).+func ValidateEmail(s string) bool {+ _, err := SanitizeEmail(s)+ return err == nil+}++// SanitizeEmail trims, lowercases, and validates s as a bare e-mail address+// (no display name) and returns the canonical form. Returns ErrInvalidEmail+// for anything `mail.ParseAddress` rejects or for input with a display name.+func SanitizeEmail(s string) (string, error) {+ s = strings.ToLower(strings.TrimSpace(s))+ em, err := mail.ParseAddress(s)+ if err != nil || em.Address != s {+ return "", ErrInvalidEmail}+ return em.Address, nil+}- return true+// ParseEmailAddress extracts the lowercased bare address from an RFC 5322+// "From"-style header value, accepting both bare addresses ("[email protected]") and+// the display-name form ("Name <[email protected]>"). Returns "" if unparseable.+func ParseEmailAddress(s string) string {+ s = strings.TrimSpace(s)+ if s == "" {+ return ""+ }+ em, err := mail.ParseAddress(s)+ if err != nil {+ return ""+ }+ return strings.ToLower(em.Address)}// GenerateRandomString generates a cryptographically random, alphanumeric string of length n.diff --git a/models/settings.go b/models/settings.goindex 14c58758..74915308 100644--- a/models/settings.go+++ b/models/settings.go@@ -81,23 +81,24 @@ type Settings struct {UploadS3Expiry string `json:"upload.s3.expiry"`SMTP []struct {- Name string `json:"name"`- UUID string `json:"uuid"`- Enabled bool `json:"enabled"`- Host string `json:"host"`- HelloHostname string `json:"hello_hostname"`- Port int `json:"port"`- AuthProtocol string `json:"auth_protocol"`- Username string `json:"username"`- Password string `json:"password,omitempty"`- EmailHeaders []map[string]string `json:"email_headers"`- MaxConns int `json:"max_conns"`- MaxMsgRetries int `json:"max_msg_retries"`- MsgRetryDelay string `json:"msg_retry_delay"`- IdleTimeout string `json:"idle_timeout"`- WaitTimeout string `json:"wait_timeout"`- TLSType string `json:"tls_type"`- TLSSkipVerify bool `json:"tls_skip_verify"`+ Name string `json:"name"`+ UUID string `json:"uuid"`+ Enabled bool `json:"enabled"`+ Host string `json:"host"`+ HelloHostname string `json:"hello_hostname"`+ Port int `json:"port"`+ AuthProtocol string `json:"auth_protocol"`+ Username string `json:"username"`+ Password string `json:"password,omitempty"`+ EmailHeaders []map[string]string `json:"email_headers"`+ MaxConns int `json:"max_conns"`+ MaxMsgRetries int `json:"max_msg_retries"`+ MsgRetryDelay string `json:"msg_retry_delay"`+ IdleTimeout string `json:"idle_timeout"`+ WaitTimeout string `json:"wait_timeout"`+ TLSType string `json:"tls_type"`+ TLSSkipVerify bool `json:"tls_skip_verify"`+ FromAddresses []string `json:"from_addresses"`} `json:"smtp"`Messengers []struct {diff --git a/schema.sql b/schema.sqlindex 1ea7eb8b..a971463c 100644--- a/schema.sql+++ b/schema.sql@@ -278,8 +278,8 @@ INSERT INTO settings (key, value) VALUES('upload.s3.bucket_type', '"public"'),('upload.s3.expiry', '"167h"'),('smtp',- '[{"enabled":true, "host":"smtp.yoursite.com","port":25,"auth_protocol":"cram","username":"username","password":"password","hello_hostname":"","max_conns":10,"idle_timeout":"15s","wait_timeout":"5s","max_msg_retries":2,"msg_retry_delay":"10ms","tls_type":"STARTTLS","tls_skip_verify":false,"email_headers":[]},- {"enabled":false, "host":"smtp.gmail.com","port":465,"auth_protocol":"login","username":"[email protected]","password":"password","hello_hostname":"","max_conns":10,"idle_timeout":"15s","wait_timeout":"5s","max_msg_retries":2,"msg_retry_delay":"10ms","tls_type":"TLS","tls_skip_verify":false,"email_headers":[]}]'),+ '[{"enabled":true, "host":"smtp.yoursite.com","port":25,"auth_protocol":"cram","username":"username","password":"password","hello_hostname":"","max_conns":10,"idle_timeout":"15s","wait_timeout":"5s","max_msg_retries":2,"msg_retry_delay":"10ms","tls_type":"STARTTLS","tls_skip_verify":false,"email_headers":[], "from_addresses":[]},+ {"enabled":false, "host":"smtp.gmail.com","port":465,"auth_protocol":"login","username":"[email protected]","password":"password","hello_hostname":"","max_conns":10,"idle_timeout":"15s","wait_timeout":"5s","max_msg_retries":2,"msg_retry_delay":"10ms","tls_type":"TLS","tls_skip_verify":false,"email_headers":[], "from_addresses":[]}]'),('messengers', '[]'),('bounce.enabled', 'false'),('bounce.webhooks_enabled', 'false'),