@@ -183,6 +183,15 @@ func (s *SMTPHandler) dispatch(subject, htmlBody, plainBody, to string) Delivery
183
183
if err != nil {
184
184
return true ,xerrors .Errorf ("message transmission: %w" ,err )
185
185
}
186
+ closeOnce := sync .OnceValue (func ()error {
187
+ return message .Close ()
188
+ })
189
+ // Close the message when this method exits in order to not leak resources. Even though we're calling this explicitly
190
+ // further down, the method may exit before then.
191
+ defer func () {
192
+ // If we try close an already-closed writer, it'll send a subsequent request to the server which is invalid.
193
+ _ = closeOnce ()
194
+ }()
186
195
187
196
// Create message headers.
188
197
msg := & bytes.Buffer {}
@@ -250,7 +259,7 @@ func (s *SMTPHandler) dispatch(subject, htmlBody, plainBody, to string) Delivery
250
259
return false ,xerrors .Errorf ("write body buffer: %w" ,err )
251
260
}
252
261
253
- if err = message . Close ();err != nil {
262
+ if err = closeOnce ();err != nil {
254
263
return true ,xerrors .Errorf ("delivery failure: %w" ,err )
255
264
}
256
265