Skip to content

Commit

Permalink
setters: q-encode headers according to RFC1342
Browse files Browse the repository at this point in the history
Encodes non-ASCII characters using the Q-encoding specified in RFC1342.

    https://tools.ietf.org/html/rfc1342

Fixes #19.
  • Loading branch information
domodwyer committed Mar 29, 2018
1 parent 136dc8c commit 5711ad5
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 2 deletions.
9 changes: 7 additions & 2 deletions setters.go
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -115,8 +117,9 @@ func (m *MailYak) From(addr string) {
//
// From Name <[email protected]>
//
// 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.
Expand All @@ -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, ""))
}
77 changes: 77 additions & 0 deletions setters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}

0 comments on commit 5711ad5

Please sign in to comment.