From 468e1e2b2ce0c961020ac754634a20d57bd3c6d2 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Mon, 20 Nov 2023 18:36:19 +0100 Subject: [PATCH] Protect against empty address list, refactor error handling Added a condition to prevent assignment of an empty address list to the 'HeaderFrom' scenario. This eliminates potential runtime errors when trying to access an nonexistent element of a slice. Adjusted error handling in the sendmail execution part by reusing the 'err' variable, promoting cleaner, more readable code. --- msg.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/msg.go b/msg.go index e623958..268349e 100644 --- a/msg.go +++ b/msg.go @@ -287,7 +287,9 @@ func (m *Msg) SetAddrHeader(h AddrHeader, v ...string) error { } switch h { case HeaderFrom: - m.addrHeader[h] = []*mail.Address{al[0]} + if len(al) > 0 { + m.addrHeader[h] = []*mail.Address{al[0]} + } default: m.addrHeader[h] = al } @@ -1001,7 +1003,7 @@ func (m *Msg) WriteToSendmailWithContext(ctx context.Context, sp string, a ...st } // Start the execution and write to STDIN - if err := ec.Start(); err != nil { + if err = ec.Start(); err != nil { return fmt.Errorf("could not start sendmail execution: %w", err) } _, err = m.WriteTo(si) @@ -1012,7 +1014,7 @@ func (m *Msg) WriteToSendmailWithContext(ctx context.Context, sp string, a ...st } // Close STDIN and wait for completion or cancellation of the sendmail executable - if err := si.Close(); err != nil { + if err = si.Close(); err != nil { return fmt.Errorf("failed to close STDIN pipe: %w", err) } @@ -1025,7 +1027,7 @@ func (m *Msg) WriteToSendmailWithContext(ctx context.Context, sp string, a ...st return fmt.Errorf("sendmail command failed: %s", string(serr)) } - if err := ec.Wait(); err != nil { + if err = ec.Wait(); err != nil { return fmt.Errorf("sendmail command execution failed: %w", err) }