Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion email.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,49 @@ func (tr *trimReader) Read(buf []byte) (int, error) {
return n, err
}

// splitAddressList splits on commas that separate addresses. A comma inside a
// quoted string or a comment is part of that address.
func splitAddressList(s string) []string {
var parts []string
var b strings.Builder
var quote, escape bool
var paren int
for _, r := range s {
if escape {
b.WriteRune(r)
escape = false
continue
}
if quote && r == '\\' {
b.WriteRune(r)
escape = true
continue
}
if r == '"' {
quote = !quote
b.WriteRune(r)
continue
}
if !quote && r == '(' {
paren++
} else if !quote && r == ')' && paren > 0 {
paren--
}
if r == ',' && !quote && paren == 0 {
parts = append(parts, b.String())
b.Reset()
continue
}
b.WriteRune(r)
}
parts = append(parts, b.String())
return parts
}

func handleAddressList(v []string) []string {
res := []string{}
for _, a := range v {
w := strings.Split(a, ",")
w := splitAddressList(a)
for _, addr := range w {
decodedAddr, err := (&mime.WordDecoder{}).DecodeHeader(strings.TrimSpace(addr))
if err == nil {
Expand Down
18 changes: 16 additions & 2 deletions email_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,20 @@ This is a test message!`)
}
}

func TestAddressListCommaInsideName(t *testing.T) {
raw := []byte("From: a@b.com\r\nTo: \"Doe, John\" <john@example.com>, Jane <jane@example.com>\r\nCc: (Doe, John) <john@example.com>\r\nSubject: hi\r\nContent-Type: text/plain\r\n\r\nhello\r\n")
e, err := NewEmailFromReader(bytes.NewReader(raw))
if err != nil {
t.Fatal(err)
}
if len(e.To) != 2 || e.To[0] != `"Doe, John" <john@example.com>` || e.To[1] != "Jane <jane@example.com>" {
t.Fatalf("To: got %#v", e.To)
}
if len(e.Cc) != 1 || e.Cc[0] != "(Doe, John) <john@example.com>" {
t.Fatalf("Cc: got %#v", e.Cc)
}
}

func TestNonMultipartEmailFromReader(t *testing.T) {
ex := &Email{
Text: []byte("This is a test message!"),
Expand Down Expand Up @@ -728,7 +742,7 @@ TGV0J3MganVzdCBwcmV0ZW5kIHRoaXMgaXMgcmF3IEpQRUcgZGF0YS4=
}
}

func ExampleGmail() {
func Example_gmail() {
e := NewEmail()
e.From = "Jordan Wright <test@gmail.com>"
e.To = []string{"test@example.com"}
Expand All @@ -740,7 +754,7 @@ func ExampleGmail() {
e.Send("smtp.gmail.com:587", smtp.PlainAuth("", e.From, "password123", "smtp.gmail.com"))
}

func ExampleAttach() {
func Example_attach() {
e := NewEmail()
e.AttachFile("test.txt")
}
Expand Down