Skip to content

Commit

Permalink
Fixes #8
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
wneessen committed May 27, 2022
1 parent 570b7bc commit ebef1fe
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
8 changes: 4 additions & 4 deletions msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
}
Expand All @@ -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...)
}
Expand Down
28 changes: 28 additions & 0 deletions msg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/mail"
"strings"
"testing"
"time"
)
Expand Down Expand Up @@ -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)
}
}

0 comments on commit ebef1fe

Please sign in to comment.