Debian Codegraph @

pkg/services/email/smtp/smtp_config.go

raw
1 package smtp
2
3 import (
4 "crypto/tls"
5 "fmt"
6 "net"
7 "net/url"
8 "slices"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/nicholas-fedor/shoutrrr/pkg/format"
14 "github.com/nicholas-fedor/shoutrrr/pkg/types"
15 "github.com/nicholas-fedor/shoutrrr/pkg/util"
16 )
17
18 // Config is the configuration needed to send e-mail notifications over SMTP.
19 type Config struct {
20 // Host is the SMTP server hostname or IP address.
21 Host string `desc:"SMTP server hostname or IP address" url:"Host"`
22 // Username is the SMTP server username.
23 Username string `default:"" desc:"SMTP server username" url:"User"`
24 // Password is the SMTP server password, or an OAuth2 access token when Auth is [AuthOAuth2].
25 Password string `default:"" desc:"SMTP server password or hash (for OAuth2)" url:"Pass"`
26 // Port is the SMTP server port. Common values are 25, 465, 587, and 2525.
27 Port uint16 `default:"25" desc:"SMTP server port, common ones are 25, 465, 587 or 2525" url:"Port"`
28 // FromAddress is the sender e-mail address.
29 FromAddress string `desc:"E-mail address that the mail are sent from" key:"fromaddress,from"`
30 // FromName is the sender display name.
31 FromName string `desc:"Name of the sender" key:"fromname" optional:"yes"`
32 // ToAddresses is the list of recipient e-mail addresses.
33 ToAddresses []string `desc:"List of recipient e-mails" key:"toaddresses,to"`
34 // Subject is the e-mail subject. It is empty when omitted.
35 Subject string `default:"" desc:"The subject of the sent mail" key:"subject,title"`
36 // Auth is the SMTP authentication method. See [AuthTypes].
37 Auth authType `default:"Unknown" desc:"SMTP authentication method" key:"auth"`
38 // Encryption is the SMTP transport encryption method. See [EncMethods].
39 Encryption encMethod `default:"Auto" desc:"Encryption method" key:"encryption"`
40 // UseStartTLS controls whether STARTTLS is attempted on non-implicit-TLS connections.
41 UseStartTLS bool `default:"Yes" desc:"Whether to use StartTLS encryption" key:"usestarttls,starttls"`
42 // UseHTML sends the message as multipart/alternative with an HTML part when true.
43 UseHTML bool `default:"No" desc:"Whether the message being sent is in HTML" key:"usehtml"`
44 // ClientHost is the hostname sent in the SMTP EHLO/HELO handshake.
45 ClientHost string `default:"localhost" desc:"SMTP client hostname" key:"clienthost"`
46 // RequireStartTLS fails the send when STARTTLS is enabled but unsupported.
47 RequireStartTLS bool `default:"No" desc:"Fail if StartTLS is enabled but unsupported" key:"requirestarttls"`
48 // SkipTLSVerify skips TLS certificate verification when true.
49 SkipTLSVerify bool `default:"No" desc:"Whether to skip TLS certificate verification" key:"skiptlsverify"`
50 // Timeout is the timeout for the SMTP connection and session.
51 Timeout time.Duration `default:"10s" desc:"Timeout for the SMTP connection and session" key:"timeout"`
52 }
53
54 // Scheme is the identifying part of this service's configuration URL.
55 const Scheme = "smtp"
56
57 // Clone returns a copy of the config.
58 //
59 // [Config.ToAddresses] is copied so later mutations do not affect the original.
60 //
61 // Returns:
62 // - A copy of the configuration with an independent recipient list.
63 func (c *Config) Clone() Config {
64 clone := *c
65 clone.ToAddresses = slices.Clone(c.ToAddresses)
66
67 return clone
68 }
69
70 // Enums returns the fields that should use a corresponding EnumFormatter to Print/Parse their values.
71 //
72 // Returns:
73 // - A map from field names to their enum formatters for [Config.Auth] and [Config.Encryption].
74 func (c *Config) Enums() map[string]types.EnumFormatter {
75 return map[string]types.EnumFormatter{
76 "Auth": AuthTypes.Enum,
77 "Encryption": EncMethods.Enum,
78 }
79 }
80
81 // GetURL returns a URL representation of its current field values.
82 //
83 // Returns:
84 // - A smtp:// URL encoding the current configuration.
85 func (c *Config) GetURL() *url.URL {
86 resolver := format.NewPropKeyResolver(c)
87
88 return c.getURL(&resolver)
89 }
90
91 // SetURL updates a [Config] from a URL representation of its field values.
92 //
93 // Parameters:
94 // - serviceURL: The SMTP configuration URL to parse.
95 //
96 // Returns:
97 // - An error if a query parameter is invalid or required addresses are missing.
98 func (c *Config) SetURL(serviceURL *url.URL) error {
99 resolver := format.NewPropKeyResolver(c)
100
101 return c.setURL(&resolver, serviceURL)
102 }
103
104 // getURL constructs a URL from the Config's fields using the provided resolver.
105 //
106 // [Config.RequireStartTLS] and [Config.SkipTLSVerify] are included only when true.
107 //
108 // Parameters:
109 // - resolver: Resolver used to serialize configuration query keys.
110 //
111 // Returns:
112 // - A smtp:// URL encoding the current configuration.
113 func (c *Config) getURL(resolver types.ConfigQueryResolver) *url.URL {
114 serviceURL := &url.URL{
115 User: util.URLUserPassword(c.Username, c.Password),
116 Host: net.JoinHostPort(c.Host, strconv.FormatUint(uint64(c.Port), 10)),
117 Path: "/",
118 Scheme: Scheme,
119 ForceQuery: true,
120 }
121 // Define primary keys in the exact order matching urlWithAllProps.
122 primaryKeys := []string{
123 "auth",
124 "clienthost",
125 "encryption",
126 "fromaddress",
127 "fromname",
128 "subject",
129 "toaddresses",
130 "usehtml",
131 "usestarttls",
132 "timeout",
133 }
134
135 queryParts := make([]string, 0, len(primaryKeys)+1)
136 for _, key := range primaryKeys {
137 value, err := resolver.Get(key)
138 if err != nil {
139 continue
140 }
141
142 queryParts = append(queryParts, fmt.Sprintf("%s=%s", key, url.QueryEscape(value)))
143 }
144 // Only include requirestarttls if explicitly set to true.
145 if c.RequireStartTLS {
146 queryParts = append(queryParts, "requirestarttls=Yes")
147 }
148 // Only include skiptlsverify if explicitly set to true.
149 if c.SkipTLSVerify {
150 queryParts = append(queryParts, "skiptlsverify=Yes")
151 }
152
153 serviceURL.RawQuery = strings.Join(queryParts, "&")
154
155 return serviceURL
156 }
157
158 // restorePlusAddresses replaces parsed spaces in e-mail addr-spec local parts with '+'.
159 //
160 // URL query parsing turns plus signs into spaces, so this restores plus-tagged
161 // addresses such as [email protected]. Display-name spaces, including those
162 // in mailbox syntax like `Name <[email protected]>`, are left unchanged.
163 func (c *Config) restorePlusAddresses() {
164 c.FromAddress = restorePlusAddress(c.FromAddress)
165 for i, adr := range c.ToAddresses {
166 c.ToAddresses[i] = restorePlusAddress(adr)
167 }
168 }
169
170 // restorePlusAddress restores plus tags in a mailbox string.
171 //
172 // If addr uses angle-bracket mailbox syntax, only the addr-spec between '<'
173 // and '>' is rewritten so display-name spaces are preserved.
174 //
175 // Parameters:
176 // - addr: A mailbox string, either a bare addr-spec or display-name <addr-spec>.
177 //
178 // Returns:
179 // - The mailbox string with plus tags restored in the addr-spec local-part.
180 func restorePlusAddress(addr string) string {
181 start := strings.LastIndex(addr, "<")
182
183 end := strings.LastIndex(addr, ">")
184 if start >= 0 && end > start {
185 return addr[:start+1] + restorePlusInAddrSpec(addr[start+1:end]) + addr[end:]
186 }
187
188 return restorePlusInAddrSpec(addr)
189 }
190
191 // restorePlusInAddrSpec restores plus tags in an RFC 5322 addr-spec.
192 //
193 // Spaces in the local-part are replaced with '+' to undo URL query decoding of
194 // plus-tagged addresses such as [email protected]. The domain is left unchanged.
195 //
196 // Parameters:
197 // - spec: An addr-spec whose plus tags may have been decoded as spaces.
198 //
199 // Returns:
200 // - The addr-spec with spaces in the local-part replaced by '+'.
201 func restorePlusInAddrSpec(spec string) string {
202 local, domain, found := strings.Cut(spec, "@")
203 if !found {
204 return strings.ReplaceAll(spec, " ", "+")
205 }
206
207 return strings.ReplaceAll(local, " ", "+") + "@" + domain
208 }
209
210 // setURL updates the Config from a URL using the provided resolver.
211 //
212 // [Config.FromAddress] and [Config.ToAddresses] are required except for the dummy URL used in tests.
213 //
214 // Parameters:
215 // - resolver: Resolver used to apply query parameters to configuration fields.
216 // - serviceURL: The SMTP configuration URL to parse.
217 //
218 // Returns:
219 // - An error if a query parameter is invalid or required addresses are missing.
220 func (c *Config) setURL(resolver types.ConfigQueryResolver, serviceURL *url.URL) error {
221 password, _ := serviceURL.User.Password()
222 c.Username = serviceURL.User.Username()
223 c.Password = password
224 c.Host = serviceURL.Hostname()
225
226 if port, err := strconv.ParseUint(serviceURL.Port(), 10, 16); err == nil {
227 c.Port = uint16(port)
228 }
229
230 for key, vals := range serviceURL.Query() {
231 if err := resolver.Set(key, vals[0]); err != nil {
232 return fmt.Errorf("setting query parameter %q to %q: %w", key, vals[0], err)
233 }
234 }
235
236 if serviceURL.String() != "smtp://[email protected]" {
237 if len(c.FromAddress) < 1 {
238 return ErrFromAddressMissing
239 }
240
241 if len(c.ToAddresses) < 1 {
242 return ErrToAddressMissing
243 }
244 }
245
246 c.restorePlusAddresses()
247
248 return nil
249 }
250
251 // newTLSConfig builds the [tls.Config] used for implicit TLS and STARTTLS.
252 //
253 // Parameters:
254 // - config: SMTP configuration providing the server name and [Config.SkipTLSVerify] flag.
255 //
256 // Returns:
257 // - A TLS config with TLS 1.2 as the minimum version. The maximum version is
258 // left unset so crypto/tls can negotiate the highest mutually supported version.
259 func newTLSConfig(config *Config) *tls.Config {
260 return &tls.Config{
261 ServerName: config.Host,
262 MinVersion: tls.VersionTLS12,
263 InsecureSkipVerify: config.SkipTLSVerify,
264 }
265 }