Debian Codegraph @

pkg/services/email/smtp/smtp.go

raw
1 package smtp
2
3 import (
4 "context"
5 "crypto/rand"
6 "crypto/tls"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io"
11 "net"
12 "net/smtp"
13 "net/url"
14 "os"
15 "strconv"
16 "strings"
17 "time"
18
19 "github.com/nicholas-fedor/shoutrrr/internal/failures"
20 "github.com/nicholas-fedor/shoutrrr/pkg/format"
21 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
22 "github.com/nicholas-fedor/shoutrrr/pkg/types"
23 )
24
25 // Service sends notifications to given email addresses via SMTP.
26 type Service struct {
27 standard.Standard
28 standard.Templater
29
30 Config *Config
31 multipartBoundary string
32 propKeyResolver format.PropKeyResolver
33 }
34
35 const (
36 contentHTML = "text/html; charset=\"UTF-8\""
37 contentPlain = "text/plain; charset=\"UTF-8\""
38 contentMultipart = "multipart/alternative; boundary=%s"
39 DefaultSMTPPort = 25 // DefaultSMTPPort is the standard port for SMTP communication.
40 boundaryByteLen = 8 // boundaryByteLen is the number of bytes for the multipart boundary.
41 DefaultTimeout = 10 // DefaultTimeout is the default timout in seconds
42 shortResponseErrorSubstring = "short response" // Error substring from textproto indicating a short response that is sometimes received during session closure.
43 )
44
45 // ErrNoAuth is a sentinel error indicating no authentication is required.
46 var ErrNoAuth = errors.New("no authentication required")
47
48 // Static errors for SMTP operations.
49 var (
50 ErrServerNoStartTLS = errors.New("server does not support StartTLS")
51 )
52
53 // GetID returns the service identifier.
54 func (s *Service) GetID() string {
55 return Scheme
56 }
57
58 // Initialize loads ServiceConfig from serviceURL and sets logger for this Service.
59 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
60 s.SetLogger(logger)
61 s.Config = &Config{
62 Port: DefaultSMTPPort,
63 ToAddresses: nil,
64 Subject: "",
65 Auth: AuthTypes.Unknown,
66 UseStartTLS: true,
67 UseHTML: false,
68 Encryption: EncMethods.Auto,
69 ClientHost: "localhost",
70 Timeout: DefaultTimeout * time.Second,
71 }
72
73 pkr := format.NewPropKeyResolver(s.Config)
74
75 if err := s.Config.setURL(&pkr, serviceURL); err != nil {
76 return err
77 }
78
79 if s.Config.Auth == AuthTypes.Unknown {
80 if s.Config.Username != "" {
81 s.Config.Auth = AuthTypes.Plain
82 } else {
83 s.Config.Auth = AuthTypes.None
84 }
85 }
86
87 s.propKeyResolver = pkr
88
89 return nil
90 }
91
92 // Send sends a notification message to email recipients.
93 func (s *Service) Send(message string, params *types.Params) error {
94 config := s.Config.Clone()
95 if err := s.propKeyResolver.UpdateConfigFromParams(&config, params); err != nil {
96 return fail(FailApplySendParams, err)
97 }
98
99 if config.SkipTLSVerify {
100 s.Log("Warning: TLS verification is disabled, making connections insecure")
101 }
102
103 ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
104 defer cancel()
105
106 client, err := getClientConnection(ctx, s.Config)
107 if err != nil {
108 return fail(FailGetSMTPClient, err)
109 }
110
111 return s.doSend(client, message, &config)
112 }
113
114 // getClientConnection establishes a connection to the SMTP server using the provided configuration.
115 func getClientConnection(ctx context.Context, config *Config) (*smtp.Client, error) {
116 var (
117 conn net.Conn
118 err error
119 )
120
121 addr := net.JoinHostPort(config.Host, strconv.FormatUint(uint64(config.Port), 10))
122
123 if useImplicitTLS(config.Encryption, config.Port) {
124 dialer := &tls.Dialer{
125 Config: &tls.Config{
126 ServerName: config.Host,
127 MinVersion: tls.VersionTLS12, // Enforce TLS 1.2 or higher
128 InsecureSkipVerify: config.SkipTLSVerify,
129 },
130 }
131 conn, err = dialer.DialContext(ctx, "tcp", addr)
132 } else {
133 dialer := &net.Dialer{}
134 conn, err = dialer.DialContext(ctx, "tcp", addr)
135 }
136
137 if err != nil {
138 return nil, fail(FailConnectToServer, err)
139 }
140
141 client, err := smtp.NewClient(conn, config.Host)
142 if err != nil {
143 return nil, fail(FailCreateSMTPClient, err)
144 }
145
146 return client, nil
147 }
148
149 // doSend sends an email message using the provided SMTP client and configuration.
150 func (s *Service) doSend(client *smtp.Client, message string, config *Config) failure {
151 config.FixEmailTags()
152
153 clientHost := s.resolveClientHost(config)
154
155 if err := client.Hello(clientHost); err != nil {
156 return fail(FailHandshake, err)
157 }
158
159 if config.UseHTML {
160 b := make([]byte, boundaryByteLen)
161 if _, err := rand.Read(b); err != nil {
162 return fail(FailUnknown, err) // Fallback error for rare case
163 }
164
165 s.multipartBoundary = hex.EncodeToString(b)
166 }
167
168 if config.UseStartTLS && !useImplicitTLS(config.Encryption, config.Port) {
169 if supported, _ := client.Extension("StartTLS"); !supported {
170 if config.RequireStartTLS {
171 return fail(FailEnableStartTLS, ErrServerNoStartTLS)
172 }
173
174 s.Logf(
175 "Warning: StartTLS enabled, but server does not support it. Connection is unencrypted",
176 )
177 } else {
178 if err := client.StartTLS(&tls.Config{
179 ServerName: config.Host,
180 MinVersion: tls.VersionTLS12,
181 MaxVersion: tls.VersionTLS13,
182 InsecureSkipVerify: config.SkipTLSVerify,
183 }); err != nil {
184 return fail(FailEnableStartTLS, err)
185 }
186 }
187 }
188
189 auth, err := s.getAuth(config)
190 if err != nil && !errors.Is(err, ErrNoAuth) {
191 return err
192 } else if auth != nil {
193 if err := client.Auth(auth); err != nil {
194 return fail(FailAuthenticating, err)
195 }
196 }
197
198 var errs []error
199
200 for _, toAddress := range config.ToAddresses {
201 if err := s.sendToRecipient(client, toAddress, config, message); err != nil {
202 errs = append(errs, fail(FailSendRecipient, err, toAddress))
203 s.Logf("Failed to send to %q: %v", toAddress, err)
204
205 continue
206 }
207
208 s.Logf("Mail successfully sent to %q!", toAddress)
209 }
210
211 // Send the QUIT command and close the connection.
212 if err := client.Quit(); err != nil {
213 // Ignore known "short response" errors from quirky servers (e.g., Office 365 on close),
214 // as they don't impact delivery.
215 if strings.Contains(err.Error(), shortResponseErrorSubstring) {
216 s.Logf("Warning: Ignoring session closure error (delivery succeeded): %v", err)
217 } else {
218 // Bubble up other close errors (e.g., network drops)
219 errs = append(errs, fail(FailClosingSession, err))
220 }
221 }
222
223 // Best-effort cleanup to avoid descriptor leaks
224 if closeErr := client.Close(); closeErr != nil {
225 s.Logf("Warning: Failed to close SMTP client connection: %v", closeErr)
226 }
227
228 if len(errs) > 0 {
229 return failures.Wrap(
230 "failed to send to some recipients",
231 FailSendRecipient,
232 errors.Join(errs...),
233 )
234 }
235
236 return nil
237 }
238
239 // getAuth returns the appropriate SMTP authentication mechanism based on the configuration.
240 //
241 //nolint:exhaustive // false positive: switch covers all AuthTypes, linter confuses local authType with net/smtp.authType
242 func (s *Service) getAuth(config *Config) (smtp.Auth, failure) {
243 switch config.Auth {
244 case AuthTypes.None:
245 return nil, fail(FailAuthType, ErrNoAuth)
246 case AuthTypes.Plain:
247 return smtp.PlainAuth("", config.Username, config.Password, config.Host), nil
248 case AuthTypes.CRAMMD5:
249 return smtp.CRAMMD5Auth(config.Username, config.Password), nil
250 case AuthTypes.OAuth2:
251 return OAuth2Auth(config.Username, config.Password), nil
252 case AuthTypes.Unknown:
253 return nil, fail(FailAuthType, nil, config.Auth.String())
254 default:
255 return nil, fail(FailAuthType, nil, config.Auth.String())
256 }
257 }
258
259 // getHeaders constructs email headers for the SMTP message.
260 func (s *Service) getHeaders(toAddress, subject string) map[string]string {
261 conf := s.Config
262
263 var contentType string
264 if conf.UseHTML {
265 contentType = fmt.Sprintf(contentMultipart, s.multipartBoundary)
266 } else {
267 contentType = contentPlain
268 }
269
270 return map[string]string{
271 "Subject": subject,
272 "Date": time.Now().Format(time.RFC1123Z),
273 "To": toAddress,
274 "From": fmt.Sprintf("%s <%s>", conf.FromName, conf.FromAddress),
275 "MIME-version": "1.0",
276 "Content-Type": contentType,
277 }
278 }
279
280 // resolveClientHost determines the client hostname to use in the SMTP handshake.
281 func (s *Service) resolveClientHost(config *Config) string {
282 if config.ClientHost != "auto" {
283 return config.ClientHost
284 }
285
286 hostname, err := os.Hostname()
287 if err != nil {
288 s.Logf("Failed to get hostname, falling back to localhost: %v", err)
289
290 return "localhost"
291 }
292
293 return hostname
294 }
295
296 // sendToRecipient sends an email to a single recipient using the provided SMTP client.
297 func (s *Service) sendToRecipient(
298 client *smtp.Client,
299 toAddress string,
300 config *Config,
301 message string,
302 ) failure {
303 // Set the sender and recipient first
304 if err := client.Mail(config.FromAddress); err != nil {
305 return fail(FailSetSender, err)
306 }
307
308 if err := client.Rcpt(toAddress); err != nil {
309 return fail(FailSetRecipient, err)
310 }
311
312 // Send the email body.
313 writeCloser, err := client.Data()
314 if err != nil {
315 return fail(FailOpenDataStream, err)
316 }
317
318 if err := writeHeaders(writeCloser, s.getHeaders(toAddress, config.Subject)); err != nil {
319 return err
320 }
321
322 var ferr failure
323 if config.UseHTML {
324 ferr = s.writeMultipartMessage(writeCloser, message)
325 } else {
326 ferr = s.writeMessagePart(writeCloser, message, "plain")
327 }
328
329 if ferr != nil {
330 return ferr
331 }
332
333 if err = writeCloser.Close(); err != nil {
334 return fail(FailCloseDataStream, err)
335 }
336
337 return nil
338 }
339
340 // writeMessagePart writes a single part of an email message using the specified template.
341 func (s *Service) writeMessagePart(
342 writeCloser io.WriteCloser,
343 message string,
344 template string,
345 ) failure {
346 if tpl, found := s.GetTemplate(template); found {
347 data := make(map[string]string)
348
349 data["message"] = message
350 if err := tpl.Execute(writeCloser, data); err != nil {
351 return fail(FailMessageTemplate, err)
352 }
353 } else {
354 content := message
355 if template == "HTML" {
356 content = fmt.Sprintf("<pre>%s</pre>", message)
357 }
358
359 if _, err := fmt.Fprint(writeCloser, content); err != nil {
360 return fail(FailMessageRaw, err)
361 }
362 }
363
364 return nil
365 }
366
367 // writeMultipartMessage writes a multipart email message to the provided writer.
368 func (s *Service) writeMultipartMessage(writeCloser io.WriteCloser, message string) failure {
369 if err := writeMultipartHeader(
370 writeCloser,
371 s.multipartBoundary,
372 contentPlain,
373 ); err != nil {
374 return fail(FailPlainHeader, err)
375 }
376
377 if err := s.writeMessagePart(writeCloser, message, "plain"); err != nil {
378 return err
379 }
380
381 if err := writeMultipartHeader(
382 writeCloser,
383 s.multipartBoundary,
384 contentHTML,
385 ); err != nil {
386 return fail(FailHTMLHeader, err)
387 }
388
389 if err := s.writeMessagePart(writeCloser, message, "HTML"); err != nil {
390 return err
391 }
392
393 if err := writeMultipartHeader(writeCloser, s.multipartBoundary, ""); err != nil {
394 return fail(FailMultiEndHeader, err)
395 }
396
397 return nil
398 }
399
400 // writeMultipartHeader writes a multipart boundary header to the provided writer.
401 func writeMultipartHeader(writeCloser io.WriteCloser, boundary, contentType string) error {
402 suffix := "\n"
403 if len(contentType) < 1 {
404 suffix = "--"
405 }
406
407 if _, err := fmt.Fprintf(writeCloser, "\n\n--%s%s", boundary, suffix); err != nil {
408 return fmt.Errorf("writing multipart boundary: %w", err)
409 }
410
411 if contentType != "" {
412 if _, err := fmt.Fprintf(writeCloser, "Content-Type: %s\n\n", contentType); err != nil {
413 return fmt.Errorf("writing content type header: %w", err)
414 }
415 }
416
417 return nil
418 }
419
420 // writeHeaders writes email headers to the provided writer.
421 func writeHeaders(writeCloser io.WriteCloser, headers map[string]string) failure {
422 for key, val := range headers {
423 if _, err := fmt.Fprintf(writeCloser, "%s: %s\n", key, val); err != nil {
424 return fail(FailWriteHeaders, err)
425 }
426 }
427
428 _, err := fmt.Fprintln(writeCloser)
429 if err != nil {
430 return fail(FailWriteHeaders, err)
431 }
432
433 return nil
434 }