From 5711ad58c40114430eed512b31acacf0167f3aaa Mon Sep 17 00:00:00 2001 From: Dom Date: Thu, 29 Mar 2018 16:14:32 +0100 Subject: [PATCH] setters: q-encode headers according to RFC1342 Encodes non-ASCII characters using the Q-encoding specified in RFC1342. https://tools.ietf.org/html/rfc1342 Fixes #19. --- setters.go | 9 ++++-- setters_test.go | 77 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/setters.go b/setters.go index 51e8755..65c4d65 100644 --- a/setters.go +++ b/setters.go @@ -1,5 +1,7 @@ package mailyak +import "mime" + // To sets a list of recipient addresses. // // You can pass one or more addresses to this method, all of which are viewable to the recipients. @@ -115,8 +117,9 @@ func (m *MailYak) From(addr string) { // // From Name // +// If name contains non-ASCII characters, it is Q-encoded according to RFC1342. func (m *MailYak) FromName(name string) { - m.fromName = m.trimRegex.ReplaceAllString(name, "") + m.fromName = mime.QEncoding.Encode("UTF-8", m.trimRegex.ReplaceAllString(name, "")) } // ReplyTo sets the Reply-To email address. @@ -127,6 +130,8 @@ func (m *MailYak) ReplyTo(addr string) { } // Subject sets the email subject line. +// +// If sub contains non-ASCII characters, it is Q-encoded according to RFC1342. func (m *MailYak) Subject(sub string) { - m.subject = m.trimRegex.ReplaceAllString(sub, "") + m.subject = mime.QEncoding.Encode("UTF-8", m.trimRegex.ReplaceAllString(sub, "")) } diff --git a/setters_test.go b/setters_test.go index 131147c..7ebff19 100644 --- a/setters_test.go +++ b/setters_test.go @@ -105,3 +105,80 @@ func TestMailYakBcc(t *testing.T) { }) } } +func TestMailYakSubject(t *testing.T) { + t.Parallel() + + tests := []struct { + // Test description. + name string + // Parameters. + subject string + // Want + want string + }{ + { + "ASCII", + "Banana\r\n", + "Banana", + }, + { + "Q-encoded", + "🍌\r\n", + "=?UTF-8?q?=F0=9F=8D=8C?=", + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + m := &MailYak{ + trimRegex: regexp.MustCompile("\r?\n"), + } + m.Subject(tt.subject) + + if !reflect.DeepEqual(m.subject, tt.want) { + t.Errorf("%q. MailYak.Subject() = %v, want %v", tt.name, m.subject, tt.want) + } + }) + } +} + +func TestMailYakFromName(t *testing.T) { + t.Parallel() + + tests := []struct { + // Test description. + name string + // Parameters. + from string + // Want + want string + }{ + { + "ASCII", + "Goat\r\n", + "Goat", + }, + { + "Q-encoded", + "🐐", + "=?UTF-8?q?=F0=9F=90=90?=", + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + m := &MailYak{ + trimRegex: regexp.MustCompile("\r?\n"), + } + m.FromName(tt.from) + + if !reflect.DeepEqual(m.fromName, tt.want) { + t.Errorf("%q. MailYak.Subject() = %v, want %v", tt.name, m.fromName, tt.want) + } + }) + } +}