From 19744cb73d273cf597cdffb4a59e0fd1942c11ea Mon Sep 17 00:00:00 2001 From: Alexandre Cesaro Date: Sat, 14 Mar 2015 20:37:43 +0100 Subject: [PATCH] Fixed name encoding in adress headers Closes #24. --- gomail.go | 36 ++++++++++++++++++++++++++++-------- gomail_test.go | 2 ++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/gomail.go b/gomail.go index 05f7808..734d881 100644 --- a/gomail.go +++ b/gomail.go @@ -12,7 +12,7 @@ import ( "sync" "time" - "gopkg.in/alexcesaro/quotedprintable.v1" + "gopkg.in/alexcesaro/quotedprintable.v2" ) // Message represents an email. @@ -104,15 +104,11 @@ const ( // SetHeader sets a value to the given header field. func (msg *Message) SetHeader(field string, value ...string) { for i := range value { - value[i] = msg.encodeHeader(value[i]) + value[i] = encodeHeader(msg.hEncoder, value[i]) } msg.header[field] = value } -func (msg *Message) encodeHeader(value string) string { - return msg.hEncoder.Encode(value) -} - // SetHeaders sets the message headers. // // Example: @@ -138,10 +134,15 @@ func (msg *Message) FormatAddress(address, name string) string { buf := getBuffer() defer putBuffer(buf) - n := msg.encodeHeader(name) - if n == name { + if !quotedprintable.NeedsEncoding(name) { quote(buf, name) } else { + var n string + if hasSpecials(name) { + n = encodeHeader(quotedprintable.B.NewHeaderEncoder(msg.charset), name) + } else { + n = encodeHeader(msg.hEncoder, name) + } buf.WriteString(n) } buf.WriteString(" <") @@ -295,6 +296,25 @@ func quote(buf *bytes.Buffer, text string) { buf.WriteByte('"') } +func hasSpecials(text string) bool { + for i := 0; i < len(text); i++ { + switch c := text[i]; c { + case '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"': + return true + } + } + + return false +} + +func encodeHeader(enc *quotedprintable.HeaderEncoder, value string) string { + if !quotedprintable.NeedsEncoding(value) { + return value + } + + return enc.Encode(value) +} + var bufPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) diff --git a/gomail_test.go b/gomail_test.go index 5b8c93b..087b7c9 100644 --- a/gomail_test.go +++ b/gomail_test.go @@ -22,6 +22,7 @@ func TestMessage(t *testing.T) { msg.SetAddressHeader("From", "from@example.com", "Señor From") msg.SetHeader("To", msg.FormatAddress("to@example.com", "Señor To"), "tobis@example.com") msg.SetAddressHeader("Cc", "cc@example.com", "A, B") + msg.SetAddressHeader("X-To", "ccbis@example.com", "à, b") msg.SetDateHeader("X-Date", stubNow()) msg.SetHeader("X-Date-2", msg.FormatDate(stubNow())) msg.SetHeader("Subject", "¡Hola, señor!") @@ -40,6 +41,7 @@ func TestMessage(t *testing.T) { content: "From: =?UTF-8?Q?Se=C3=B1or_From?= \r\n" + "To: =?UTF-8?Q?Se=C3=B1or_To?= , tobis@example.com\r\n" + "Cc: \"A, B\" \r\n" + + "X-To: =?UTF-8?B?w6AsIGI=?= \r\n" + "X-Date: Wed, 25 Jun 2014 17:46:00 +0000\r\n" + "X-Date-2: Wed, 25 Jun 2014 17:46:00 +0000\r\n" + "X-Headers: Test, =?UTF-8?Q?Caf=C3=A9?=\r\n" +