Debian Codegraph @

pkg/services/email/smtp/smtp.go

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