From ef86a1a1fb4e9659cc82db9d3033ce39a52e2db3 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Wed, 31 Jan 2024 16:28:41 +0100 Subject: [PATCH] Add Charset support for message parts Charset support has been added in the 'Part' struct. A 'SetCharset' method and a 'WithPartCharset' option have been added to override the default Part charset. The 'writePart' function in msgWriter now accommodates the charset defined at the Part level, defaulting to the previous functionality if not set. --- msg.go | 1 + msgwriter.go | 6 +++++- part.go | 13 +++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/msg.go b/msg.go index c97fc01..7ca73ce 100644 --- a/msg.go +++ b/msg.go @@ -1141,6 +1141,7 @@ func (m *Msg) hasPGPType() bool { func (m *Msg) newPart(ct ContentType, o ...PartOption) *Part { p := &Part{ ctype: ct, + cset: m.charset, enc: m.encoding, } diff --git a/msgwriter.go b/msgwriter.go index cbf0a8f..b2ff118 100644 --- a/msgwriter.go +++ b/msgwriter.go @@ -245,7 +245,11 @@ func (mw *msgWriter) newPart(h map[string][]string) { // writePart writes the corresponding part to the Msg body func (mw *msgWriter) writePart(p *Part, cs Charset) { - ct := fmt.Sprintf("%s; charset=%s", p.ctype, cs) + pcs := p.cset + if pcs.String() == "" { + pcs = cs + } + ct := fmt.Sprintf("%s; charset=%s", p.ctype, pcs) cte := p.enc.String() if mw.d == 0 { mw.writeHeader(HeaderContentType, ct) diff --git a/part.go b/part.go index 1e4d6cd..cd2219d 100644 --- a/part.go +++ b/part.go @@ -15,6 +15,7 @@ type PartOption func(*Part) // Part is a part of the Msg type Part struct { ctype ContentType + cset Charset desc string enc Encoding del bool @@ -61,6 +62,11 @@ func (p *Part) SetContentType(c ContentType) { p.ctype = c } +// SetCharset overrides the Charset of the Part +func (p *Part) SetCharset(c Charset) { + p.cset = c +} + // SetEncoding creates a new mime.WordEncoder based on the encoding setting of the message func (p *Part) SetEncoding(e Encoding) { p.enc = e @@ -82,6 +88,13 @@ func (p *Part) Delete() { p.del = true } +// WithPartCharset overrides the default Part charset +func WithPartCharset(c Charset) PartOption { + return func(p *Part) { + p.cset = c + } +} + // WithPartEncoding overrides the default Part encoding func WithPartEncoding(e Encoding) PartOption { return func(p *Part) {