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.
This commit is contained in:
Winni Neessen 2022-05-27 12:47:33 +02:00
parent 570b7bc2ed
commit ebef1fe476
Signed by: wneessen
GPG key ID: 385AC9889632126E
2 changed files with 32 additions and 4 deletions

8
msg.go
View file

@ -390,8 +390,8 @@ func (m *Msg) GetRecipients() ([]string, error) {
func (m *Msg) SetBodyString(ct ContentType, b string, o ...PartOption) { func (m *Msg) SetBodyString(ct ContentType, b string, o ...PartOption) {
buf := bytes.NewBufferString(b) buf := bytes.NewBufferString(b)
w := func(w io.Writer) (int64, error) { w := func(w io.Writer) (int64, error) {
nb, err := io.Copy(w, buf) nb, err := w.Write(buf.Bytes())
return nb, err return int64(nb), err
} }
m.SetBodyWriter(ct, w, o...) 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) { func (m *Msg) AddAlternativeString(ct ContentType, b string, o ...PartOption) {
buf := bytes.NewBufferString(b) buf := bytes.NewBufferString(b)
w := func(w io.Writer) (int64, error) { w := func(w io.Writer) (int64, error) {
nb, err := io.Copy(w, buf) nb, err := w.Write(buf.Bytes())
return nb, err return int64(nb), err
} }
m.AddAlternativeWriter(ct, w, o...) m.AddAlternativeWriter(ct, w, o...)
} }

View file

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"io" "io"
"net/mail" "net/mail"
"strings"
"testing" "testing"
"time" "time"
) )
@ -1244,3 +1245,30 @@ func TestMsg_appendFile(t *testing.T) {
t.Errorf("appendFile() failed. Expected length: %d, got: %d", 2, len(fl)) 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)
}
}