Skip to content

Commit

Permalink
add more details when failing to parse email addresses to make findin…
Browse files Browse the repository at this point in the history
…g problems with input easier
  • Loading branch information
Julius Foitzik committed Jul 5, 2021
1 parent f59b9b8 commit 22eaa21
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
21 changes: 21 additions & 0 deletions message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mail
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"path/filepath"
Expand Down Expand Up @@ -380,6 +381,26 @@ func TestRename(t *testing.T) {
testMessage(t, m, 1, want)
}

func TestEmptyAddress(t *testing.T) {
cases := []struct {
headerName string
value string
}{
{headerName: "From", value: ""},
{headerName: "To", value: ""},
}
for i, tc := range cases {
t.Run(fmt.Sprintf("case_%d", i), func(t *testing.T) {
m := NewMessage()
m.SetHeader(tc.headerName, tc.value)
err := Send(stubSendMail(t, 1, nil), m)
if err == nil {
t.Error("expected error but got none")
}
})
}
}

func TestAttachmentsOnly(t *testing.T) {
m := NewMessage()
m.SetHeader("From", "[email protected]")
Expand Down
12 changes: 7 additions & 5 deletions send.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,17 @@ func send(s Sender, m *Message) error {
}

func (m *Message) getFrom() (string, error) {
fieldName := "Sender"
from := m.header["Sender"]
if len(from) == 0 {
from = m.header["From"]
if len(from) == 0 {
return "", errors.New(`gomail: invalid message, "From" field is absent`)
}
fieldName = "From"
}

return parseAddress(from[0])
return parseAddress(fieldName, from[0])
}

func (m *Message) getRecipients() ([]string, error) {
Expand All @@ -85,7 +87,7 @@ func (m *Message) getRecipients() ([]string, error) {
for _, field := range []string{"To", "Cc", "Bcc"} {
if addresses, ok := m.header[field]; ok {
for _, a := range addresses {
addr, err := parseAddress(a)
addr, err := parseAddress(field, a)
if err != nil {
return nil, err
}
Expand All @@ -107,10 +109,10 @@ func addAddress(list []string, addr string) []string {
return append(list, addr)
}

func parseAddress(field string) (string, error) {
addr, err := stdmail.ParseAddress(field)
func parseAddress(fieldName, fieldValue string) (string, error) {
addr, err := stdmail.ParseAddress(fieldValue)
if err != nil {
return "", fmt.Errorf("gomail: invalid address %q: %v", field, err)
return "", fmt.Errorf("gomail: invalid address %q for field %q: %v", fieldValue, fieldName, err)
}
return addr.Address, nil
}

0 comments on commit 22eaa21

Please sign in to comment.