diff --git a/gomail.go b/gomail.go index 1466943..c3b7b24 100644 --- a/gomail.go +++ b/gomail.go @@ -134,7 +134,12 @@ func (msg *Message) SetAddressHeader(field, address, name string) { // FormatAddress formats an address and a name as a valid RFC 5322 address. func (msg *Message) FormatAddress(address, name string) string { - return msg.encodeHeader(name) + " <" + address + ">" + n := msg.encodeHeader(name) + if n == name { + n = quote(name) + } + + return n + " <" + address + ">" } // SetDateHeader sets a date to the given header field. @@ -269,3 +274,16 @@ func (msg *Message) Embed(image ...*File) { // Stubbed out for testing. var readFile = ioutil.ReadFile + +func quote(text string) string { + buf := bytes.NewBufferString(`"`) + for i := 0; i < len(text); i++ { + if text[i] == '\\' || text[i] == '"' { + buf.WriteByte('\\') + } + buf.WriteByte(text[i]) + } + buf.WriteByte('"') + + return buf.String() +} diff --git a/gomail_test.go b/gomail_test.go index a7518bb..5b8c93b 100644 --- a/gomail_test.go +++ b/gomail_test.go @@ -21,6 +21,7 @@ func TestMessage(t *testing.T) { msg := NewMessage() 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.SetDateHeader("X-Date", stubNow()) msg.SetHeader("X-Date-2", msg.FormatDate(stubNow())) msg.SetHeader("Subject", "¡Hola, señor!") @@ -34,9 +35,11 @@ func TestMessage(t *testing.T) { to: []string{ "to@example.com", "tobis@example.com", + "cc@example.com", }, 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-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" +