Skip to content

Commit

Permalink
Format From, To, Cc & Bcc for RFC1342 (#115)
Browse files Browse the repository at this point in the history
* Format From, To, Cc & Bcc for RFC1342

* Fixed seperator & added tests
  • Loading branch information
Fank committed Jun 2, 2020
1 parent 8694dac commit fd8a762
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ _cgo_export.*
_testmain.go

*.exe

# IDEs
.idea
12 changes: 12 additions & 0 deletions email.go
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,18 @@ func headerToBytes(buff io.Writer, header textproto.MIMEHeader) {
switch {
case field == "Content-Type" || field == "Content-Disposition":
buff.Write([]byte(subval))
case field == "From" || field == "To" || field == "Cc" || field == "Bcc":
participants := strings.Split(subval, ",")
for i, v := range participants {
addr, err := mail.ParseAddress(v)
if err != nil {
continue
}
if addr.Name != "" {
participants[i] = fmt.Sprintf("%s <%s>", mime.QEncoding.Encode("UTF-8", addr.Name), addr.Address)
}
}
buff.Write([]byte(strings.Join(participants, ", ")))
default:
buff.Write([]byte(mime.QEncoding.Encode("UTF-8", subval)))
}
Expand Down
47 changes: 47 additions & 0 deletions email_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package email

import (
"fmt"
"strings"
"testing"

Expand Down Expand Up @@ -317,6 +318,52 @@ func TestEmailAttachment(t *testing.T) {
}
}

func TestHeaderEncoding(t *testing.T) {
cases := []struct {
field string
have string
want string
}{
{
field: "From",
have: "Needs Encóding <[email protected]>, Only ASCII <[email protected]>",
want: "=?UTF-8?q?Needs_Enc=C3=B3ding?= <[email protected]>, Only ASCII <[email protected]>\r\n",
},
{
field: "To",
have: "Keith Moore <[email protected]>, Keld Jørn Simonsen <[email protected]>",
want: "Keith Moore <[email protected]>, =?UTF-8?q?Keld_J=C3=B8rn_Simonsen?= <[email protected]>\r\n",
},
{
field: "Cc",
have: "Needs Encóding <[email protected]>",
want: "=?UTF-8?q?Needs_Enc=C3=B3ding?= <[email protected]>\r\n",
},
{
field: "Subject",
have: "Subject with a 🐟",
want: "=?UTF-8?q?Subject_with_a_=F0=9F=90=9F?=\r\n",
},
{
field: "Subject",
have: "Subject with only ASCII",
want: "Subject with only ASCII\r\n",
},
}
buff := &bytes.Buffer{}
for _, c := range cases {
header := make(textproto.MIMEHeader)
header.Add(c.field, c.have)
buff.Reset()
headerToBytes(buff, header)
want := fmt.Sprintf("%s: %s", c.field, c.want)
got := buff.String()
if got != want {
t.Errorf("invalid utf-8 header encoding. \nwant:%#v\ngot: %#v", want, got)
}
}
}

func TestEmailFromReader(t *testing.T) {
ex := &Email{
Subject: "Test Subject",
Expand Down

0 comments on commit fd8a762

Please sign in to comment.