| 1 |
package smtp |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto/tls" |
| 6 |
"net" |
| 7 |
"net/smtp" |
| 8 |
"strconv" |
| 9 |
|
| 10 |
"github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 11 |
) |
| 12 |
|
| 13 |
// dialClient establishes a connection to the SMTP server using the provided configuration. |
| 14 |
// |
| 15 |
// A custom dial function is used when non-nil; otherwise a default [net.Dialer] |
| 16 |
// opens the TCP connection. Implicit TLS is applied after the TCP dial when |
| 17 |
// [useImplicitTLS] reports that it is required. The context deadline is applied |
| 18 |
// to the connection when present. |
| 19 |
// |
| 20 |
// Parameters: |
| 21 |
// - ctx: Context that bounds dialing and the connection deadline. |
| 22 |
// - config: SMTP configuration providing host, port, encryption, and TLS options. |
| 23 |
// - dial: Optional custom TCP dial function. Nil uses [net.Dialer.DialContext]. |
| 24 |
// |
| 25 |
// Returns: |
| 26 |
// - An [smtp.Client] wrapping the established connection. |
| 27 |
// - An error if dialing, applying the deadline, or creating the client fails. |
| 28 |
func dialClient(ctx context.Context, config *Config, dial types.DialContextFunc) (*smtp.Client, error) { |
| 29 |
addr := net.JoinHostPort(config.Host, strconv.FormatUint(uint64(config.Port), 10)) |
| 30 |
|
| 31 |
if dial == nil { |
| 32 |
dial = (&net.Dialer{}).DialContext |
| 33 |
} |
| 34 |
|
| 35 |
conn, err := dial(ctx, "tcp", addr) |
| 36 |
if err != nil { |
| 37 |
return nil, fail(FailConnectToServer, err) |
| 38 |
} |
| 39 |
|
| 40 |
if useImplicitTLS(config.Encryption, config.Port) { |
| 41 |
tlsConn := tls.Client(conn, newTLSConfig(config)) |
| 42 |
if err := tlsConn.HandshakeContext(ctx); err != nil { |
| 43 |
_ = conn.Close() |
| 44 |
|
| 45 |
return nil, fail(FailConnectToServer, err) |
| 46 |
} |
| 47 |
|
| 48 |
conn = tlsConn |
| 49 |
} |
| 50 |
|
| 51 |
if deadline, ok := ctx.Deadline(); ok { |
| 52 |
if err := conn.SetDeadline(deadline); err != nil { |
| 53 |
_ = conn.Close() |
| 54 |
|
| 55 |
return nil, fail(FailConnectToServer, err) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
client, err := smtp.NewClient(conn, config.Host) |
| 60 |
if err != nil { |
| 61 |
_ = conn.Close() |
| 62 |
|
| 63 |
return nil, fail(FailCreateSMTPClient, err) |
| 64 |
} |
| 65 |
|
| 66 |
return client, nil |
| 67 |
} |