Added quotes to names in address headers

Closes #23.
This commit is contained in:
Alexandre Cesaro 2015-03-14 18:41:58 +01:00
parent c7ca0f5da9
commit 6a52a50597
2 changed files with 22 additions and 1 deletions

View File

@ -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()
}

View File

@ -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?= <from@example.com>\r\n" +
"To: =?UTF-8?Q?Se=C3=B1or_To?= <to@example.com>, tobis@example.com\r\n" +
"Cc: \"A, B\" <cc@example.com>\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" +