diff --git a/mail/header.go b/mail/header.go index 316e5ca..4bd7d54 100644 --- a/mail/header.go +++ b/mail/header.go @@ -243,7 +243,11 @@ func (h *Header) AddressList(key string) ([]*Address, error) { // // This can be used on From, Sender, Reply-To, To, Cc and Bcc header fields. func (h *Header) SetAddressList(key string, addrs []*Address) { - h.Set(key, formatAddressList(addrs)) + if len(addrs) > 0 { + h.Set(key, formatAddressList(addrs)) + } else { + h.Del(key) + } } // Date parses the Date header field. diff --git a/mail/header_test.go b/mail/header_test.go index 0c21e38..58975c0 100644 --- a/mail/header_test.go +++ b/mail/header_test.go @@ -1,8 +1,11 @@ package mail_test import ( + "bufio" + "bytes" netmail "net/mail" "reflect" + "strings" "testing" "time" @@ -176,3 +179,39 @@ func TestHeader_CanUseNetMailAddress(t *testing.T) { t.Errorf("Expected header address list to be %v, but got %v", netfrom, got) } } + +func TestHeader_EmptyAddressList(t *testing.T) { + tests := []struct { + key string + list []*mail.Address + unset bool + }{ + {"cc", nil, false}, + {"to", []*mail.Address{}, false}, + {"cc", []*mail.Address{{"Mitsuha Miyamizu", "mitsuha.miyamizu@example.org"}}, true}, + } + + for _, test := range tests { + var h mail.Header + h.SetAddressList(test.key, test.list) + if test.unset { + h.SetAddressList(test.key, nil) + } + buf := bytes.NewBuffer(nil) + w, err := mail.CreateSingleInlineWriter(buf, h) + if err != nil { + t.Error("Expected no error while creating inline writer, got:", err) + } + if err := w.Close(); err != nil { + t.Error("Expected no error while closing inline writer, got:", err) + } + scanner := bufio.NewScanner(buf) + for scanner.Scan() { + line := strings.ToLower(scanner.Text()) + if strings.HasPrefix(line, test.key) { + t.Error("Expected no address list header field, but got:", scanner.Text()) + } + } + } + +}