Debian Codegraph @

pkg/services/email/smtp/smtp.go

raw
1 package smtp
2
3 import (
4 "context"
5 "net/url"
6 "time"
7
8 "github.com/nicholas-fedor/shoutrrr/pkg/format"
9 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
10 "github.com/nicholas-fedor/shoutrrr/pkg/types"
11 )
12
13 // Service sends notifications to given email addresses via SMTP.
14 type Service struct {
15 // Standard provides logging and other base service behavior.
16 standard.Standard
17 // Templater provides named message templates for plain and HTML parts.
18 standard.Templater
19
20 // Config holds SMTP server, authentication, and message options.
21 Config *Config
22 // propKeyResolver applies URL and send-parameter overrides to [Config].
23 propKeyResolver format.PropKeyResolver
24 // dialContext, if non-nil, is used for the SMTP TCP dial.
25 dialContext types.DialContextFunc
26 }
27
28 const (
29 // DefaultSMTPPort is the standard port for SMTP communication.
30 DefaultSMTPPort = 25
31 // defaultTimeout is the default SMTP timeout.
32 defaultTimeout = 10 * time.Second
33 )
34
35 var (
36 _ types.ContextSender = (*Service)(nil)
37 _ types.DialContextSetter = (*Service)(nil)
38 )
39
40 // GetID returns the service identifier.
41 //
42 // Returns:
43 // - The scheme name [Scheme].
44 func (s *Service) GetID() string {
45 return Scheme
46 }
47
48 // Initialize loads [Config] from serviceURL and sets logger for this [Service].
49 //
50 // It applies SMTP defaults, parses the configuration URL, and infers Auth as
51 // [AuthPlain] when a username is present or [AuthNone] otherwise if
52 // Auth is [AuthUnknown].
53 //
54 // Parameters:
55 // - serviceURL: The SMTP configuration URL.
56 // - logger: Logger used for service output ([types.StdLogger]).
57 //
58 // Returns:
59 // - An error if the configuration URL is invalid.
60 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
61 s.SetLogger(logger)
62 s.Config = &Config{
63 Port: DefaultSMTPPort,
64 ToAddresses: nil,
65 Subject: "",
66 Auth: AuthTypes.Unknown,
67 UseStartTLS: true,
68 UseHTML: false,
69 Encryption: EncMethods.Auto,
70 ClientHost: "localhost",
71 Timeout: defaultTimeout,
72 }
73
74 pkr := format.NewPropKeyResolver(s.Config)
75
76 if err := s.Config.setURL(&pkr, serviceURL); err != nil {
77 return err
78 }
79
80 if s.Config.Auth == AuthTypes.Unknown {
81 if s.Config.Username != "" {
82 s.Config.Auth = AuthTypes.Plain
83 } else {
84 s.Config.Auth = AuthTypes.None
85 }
86 }
87
88 s.propKeyResolver = pkr
89
90 return nil
91 }
92
93 // Send sends a notification message to email recipients.
94 //
95 // It delegates to [Service.SendContext] with [context.Background].
96 //
97 // Parameters:
98 // - message: The notification body sent as the email message.
99 // - params: Optional runtime overrides for configuration fields ([types.Params]).
100 //
101 // Returns:
102 // - An error if configuration updates, connection, or delivery fail.
103 func (s *Service) Send(message string, params *types.Params) error {
104 return s.SendContext(context.Background(), message, params)
105 }
106
107 // SendContext sends a notification message to email recipients.
108 //
109 // It clones the service configuration, applies optional runtime params, opens
110 // an SMTP client, and delivers the message. A timeout from [Config.Timeout]
111 // bounds the connection and session, derived from ctx so caller cancellation
112 // and deadlines propagate. Non-positive timeouts use [defaultTimeout].
113 //
114 // Parameters:
115 // - ctx: Parent context for cancellation and deadlines.
116 // - message: The notification body sent as the email message.
117 // - params: Optional runtime overrides for configuration fields ([types.Params]).
118 //
119 // Returns:
120 // - An error if configuration updates, connection, or delivery fail.
121 func (s *Service) SendContext(ctx context.Context, message string, params *types.Params) error {
122 config := s.Config.Clone()
123 if err := s.propKeyResolver.UpdateConfigFromParams(&config, params); err != nil {
124 return fail(FailApplySendParams, err)
125 }
126
127 if config.SkipTLSVerify {
128 s.Log("Warning: TLS verification is disabled, making connections insecure")
129 }
130
131 ctx, cancel := context.WithTimeout(
132 ctx,
133 effectiveTimeout(config.Timeout),
134 )
135 defer cancel()
136
137 client, err := dialClient(ctx, &config, s.dialContext)
138 if err != nil {
139 return fail(FailGetSMTPClient, err)
140 }
141
142 return (&session{
143 client: client,
144 config: &config,
145 svc: s,
146 closed: false,
147 }).run(message)
148 }
149
150 // SetDialContext sets a custom dial function for SMTP TCP connections.
151 //
152 // TLS wrapping for implicit TLS still happens after the TCP dial.
153 // A nil dial restores the default [net.Dialer].
154 //
155 // Parameters:
156 // - dial: The dial function. Must be safe for concurrent use when non-nil.
157 func (s *Service) SetDialContext(dial types.DialContextFunc) {
158 s.dialContext = dial
159 }
160
161 // effectiveTimeout returns a positive SMTP timeout.
162 //
163 // Non-positive values fall back to [defaultTimeout] so [context.WithTimeout]
164 // always bounds the connection and session.
165 //
166 // Parameters:
167 // - timeout: The configured session timeout.
168 //
169 // Returns:
170 // - timeout when it is positive; otherwise [defaultTimeout].
171 func effectiveTimeout(timeout time.Duration) time.Duration {
172 if timeout <= 0 {
173 return defaultTimeout
174 }
175
176 return timeout
177 }