Refactor error handling for non-TLS SMTP connections

Introduce a global error variable for non-TLS connections and update corresponding error handling across the codebase. This enhances readability and maintainability of the error management logic.
This commit is contained in:
Winni Neessen 2024-10-01 17:23:29 +02:00
parent 5058fd5222
commit 15b9ddf067
Signed by: wneessen
GPG key ID: 385AC9889632126E
2 changed files with 12 additions and 2 deletions

View file

@ -750,8 +750,14 @@ func (c *Client) tls() error {
} }
tlsConnState, err := c.smtpClient.GetTLSConnectionState() tlsConnState, err := c.smtpClient.GetTLSConnectionState()
if err != nil { if err != nil {
switch {
case errors.Is(err, smtp.ErrNonTLSConnection):
c.isEncrypted = false
return nil
default:
return fmt.Errorf("failed to get TLS connection state: %w", err) return fmt.Errorf("failed to get TLS connection state: %w", err)
} }
}
c.isEncrypted = tlsConnState.HandshakeComplete c.isEncrypted = tlsConnState.HandshakeComplete
} }
return nil return nil

View file

@ -36,6 +36,10 @@ import (
"github.com/wneessen/go-mail/log" "github.com/wneessen/go-mail/log"
) )
var (
ErrNonTLSConnection = errors.New("connection is not using TLS")
)
// A Client represents a client connection to an SMTP server. // A Client represents a client connection to an SMTP server.
type Client struct { type Client struct {
// Text is the textproto.Conn used by the Client. It is exported to allow for clients to add extensions. // Text is the textproto.Conn used by the Client. It is exported to allow for clients to add extensions.
@ -572,7 +576,7 @@ func (c *Client) GetTLSConnectionState() (*tls.ConnectionState, error) {
defer c.mutex.RUnlock() defer c.mutex.RUnlock()
if !c.tls { if !c.tls {
return nil, errors.New("smtp: connection is not using TLS") return nil, ErrNonTLSConnection
} }
if c.conn == nil { if c.conn == nil {
return nil, errors.New("smtp: connection is not established") return nil, errors.New("smtp: connection is not established")