From ebef1fe476c3e1d2c2c1bbdb5c4493e80b68777d Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Fri, 27 May 2022 12:47:33 +0200 Subject: [PATCH] Fixes #8 We were using `io.Copy` to write to the body string/alternative string to the io.Writer. This placed the byte position of the buffer to be at the EOF after the first `WriteTo()` call leaving the output of a 2nd call to `WriteTo()` empty. --- msg.go | 8 ++++---- msg_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) 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) + } +}