From 15b9ddf0675fbceeff3091248030eea511df2bc2 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Tue, 1 Oct 2024 17:23:29 +0200 Subject: [PATCH] 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. --- client.go | 8 +++++++- smtp/smtp.go | 6 +++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/client.go b/client.go index acfeaa2..5d0e797 100644 --- a/client.go +++ b/client.go @@ -750,7 +750,13 @@ func (c *Client) tls() error { } tlsConnState, err := c.smtpClient.GetTLSConnectionState() if err != nil { - return fmt.Errorf("failed to get TLS connection state: %w", err) + switch { + case errors.Is(err, smtp.ErrNonTLSConnection): + c.isEncrypted = false + return nil + default: + return fmt.Errorf("failed to get TLS connection state: %w", err) + } } c.isEncrypted = tlsConnState.HandshakeComplete } diff --git a/smtp/smtp.go b/smtp/smtp.go index e834a09..0352133 100644 --- a/smtp/smtp.go +++ b/smtp/smtp.go @@ -36,6 +36,10 @@ import ( "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. type Client struct { // 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() if !c.tls { - return nil, errors.New("smtp: connection is not using TLS") + return nil, ErrNonTLSConnection } if c.conn == nil { return nil, errors.New("smtp: connection is not established")