From 9724a2b52330673f71b85a5e8e9bc9536fb259c0 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Sat, 28 Jan 2023 14:39:14 +0100 Subject: [PATCH 1/2] Introducing Msg part deletion This PR introduces a new struct field for the message parts: `del` If the del flag is set to `true`, the msgWriter will ignore this part during the writing process. Additionally, the `part` has now a `Delete` method that lets the user mark the part as deleted This allows middleware to take further control of the Msg and is part of #107 --- msg.go | 8 +++++++- msgwriter.go | 4 +++- part.go | 7 +++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/msg.go b/msg.go index 430feb2..77f9297 100644 --- a/msg.go +++ b/msg.go @@ -989,7 +989,13 @@ func (m *Msg) encodeString(s string) string { // hasAlt returns true if the Msg has more than one part func (m *Msg) hasAlt() bool { - return len(m.parts) > 1 + c := 0 + for _, p := range m.parts { + if !p.del { + c++ + } + } + return c > 1 } // hasMixed returns true if the Msg has mixed parts diff --git a/msgwriter.go b/msgwriter.go index d53be21..719d7df 100644 --- a/msgwriter.go +++ b/msgwriter.go @@ -102,7 +102,9 @@ func (mw *msgWriter) writeMsg(m *Msg) { } for _, p := range m.parts { - mw.writePart(p, m.charset) + if !p.del { + mw.writePart(p, m.charset) + } } if m.hasAlt() { mw.stopMP() diff --git a/part.go b/part.go index ebd0163..35c1bd0 100644 --- a/part.go +++ b/part.go @@ -16,6 +16,7 @@ type PartOption func(*Part) type Part struct { ctype ContentType enc Encoding + del bool w func(io.Writer) (int64, error) } @@ -64,6 +65,12 @@ func (p *Part) SetWriteFunc(w func(io.Writer) (int64, error)) { p.w = w } +// Delete removes the current part from the parts list of the Msg by setting the +// del flag to true. The msgWriter will skip it then +func (p *Part) Delete() { + p.del = true +} + // WithPartEncoding overrides the default Part encoding func WithPartEncoding(e Encoding) PartOption { return func(p *Part) { From c602ba103f53c2635a4f8fc3fcd874d67c9d3a33 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Sat, 28 Jan 2023 14:42:29 +0100 Subject: [PATCH 2/2] Test for message part deletion Added a test for the `Part.Delete` method --- part_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/part_test.go b/part_test.go index 55bc82d..d3ceef2 100644 --- a/part_test.go +++ b/part_test.go @@ -241,6 +241,22 @@ func TestPart_SetContent(t *testing.T) { } } +// TestPart_Delete tests Part.Delete +func TestPart_Delete(t *testing.T) { + c := "This is a test with ümläutß" + m := NewMsg() + m.SetBodyString(TypeTextPlain, c) + pl, err := getPartList(m) + if err != nil { + t.Errorf("failed: %s", err) + return + } + pl[0].Delete() + if !pl[0].del { + t.Errorf("Delete failed. Expected: %t, got: %t", true, pl[0].del) + } +} + // getPartList is a helper function func getPartList(m *Msg) ([]*Part, error) { pl := m.GetParts()