Skip to content

Commit

Permalink
Added stripping of whitespace at the beginning of emails when importi…
Browse files Browse the repository at this point in the history
…ng from a reader.
  • Loading branch information
jordan-wright committed Mar 1, 2016
1 parent f57f486 commit a62870b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
18 changes: 17 additions & 1 deletion email.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"path/filepath"
"strings"
"time"
"unicode"
)

const (
Expand Down Expand Up @@ -61,12 +62,27 @@ func NewEmail() *Email {
return &Email{Headers: textproto.MIMEHeader{}}
}

// trimReader is a custom io.Reader that will trim any leading
// whitespace, as this can cause email imports to fail.
type trimReader struct {
rd io.Reader
}

// Read trims off any unicode whitespace from the originating reader
func (tr trimReader) Read(buf []byte) (int, error) {
n, err := tr.rd.Read(buf)
t := bytes.TrimLeftFunc(buf[:n], unicode.IsSpace)
n = copy(buf, t)
return n, err
}

// NewEmailFromReader reads a stream of bytes from an io.Reader, r,
// and returns an email struct containing the parsed data.
// This function expects the data in RFC 5322 format.
func NewEmailFromReader(r io.Reader) (*Email, error) {
e := NewEmail()
tp := textproto.NewReader(bufio.NewReader(r))
s := trimReader{rd: r}
tp := textproto.NewReader(bufio.NewReader(s))
// Parse the main headers
hdrs, err := tp.ReadMIMEHeader()
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion email_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ func TestEmailFromReader(t *testing.T) {
Text: []byte("This is a test email with HTML Formatting. It also has very long lines so\nthat the content must be wrapped if using quoted-printable decoding.\n"),
HTML: []byte("<div dir=\"ltr\">This is a test email with <b>HTML Formatting.</b>\u00a0It also has very long lines so that the content must be wrapped if using quoted-printable decoding.</div>\n"),
}
raw := []byte(`MIME-Version: 1.0
raw := []byte(`
MIME-Version: 1.0
Subject: Test Subject
From: Jordan Wright <[email protected]>
To: Jordan Wright <[email protected]>
Expand Down

0 comments on commit a62870b

Please sign in to comment.