diff --git a/msg.go b/msg.go index 6e339700..b55daa82 100644 --- a/msg.go +++ b/msg.go @@ -390,8 +390,8 @@ func (m *Msg) GetRecipients() ([]string, error) { func (m *Msg) SetBodyString(ct ContentType, b string, o ...PartOption) { buf := bytes.NewBufferString(b) w := func(w io.Writer) (int64, error) { - nb, err := io.Copy(w, buf) - return nb, err + nb, err := w.Write(buf.Bytes()) + return int64(nb), err } m.SetBodyWriter(ct, w, o...) } @@ -407,8 +407,8 @@ func (m *Msg) SetBodyWriter(ct ContentType, w func(io.Writer) (int64, error), o func (m *Msg) AddAlternativeString(ct ContentType, b string, o ...PartOption) { buf := bytes.NewBufferString(b) w := func(w io.Writer) (int64, error) { - nb, err := io.Copy(w, buf) - return nb, err + nb, err := w.Write(buf.Bytes()) + return int64(nb), err } m.AddAlternativeWriter(ct, w, o...) } diff --git a/msg_test.go b/msg_test.go index 9307de48..73877401 100644 --- a/msg_test.go +++ b/msg_test.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/mail" + "strings" "testing" "time" ) @@ -1244,3 +1245,30 @@ func TestMsg_appendFile(t *testing.T) { t.Errorf("appendFile() failed. Expected length: %d, got: %d", 2, len(fl)) } } + +// TestMsg_multipleWrites tests multiple executions of WriteTo on the Msg +func TestMsg_multipleWrites(t *testing.T) { + ts := "XXX_UNIQUE_STRING_XXX" + wbuf := bytes.Buffer{} + m := NewMsg() + m.SetBodyString(TypeTextPlain, ts) + + // First WriteTo() + _, err := m.WriteTo(&wbuf) + if err != nil { + t.Errorf("failed to write body to buffer: %s", err) + } + if !strings.Contains(wbuf.String(), ts) { + t.Errorf("first WriteTo() body does not contain unique string: %s", ts) + } + + // Second WriteTo() + wbuf.Reset() + _, err = m.WriteTo(&wbuf) + if err != nil { + t.Errorf("failed to write body to buffer: %s", err) + } + if !strings.Contains(wbuf.String(), ts) { + t.Errorf("second WriteTo() body does not contain unique string: %s", ts) + } +}