Skip to content

Commit

Permalink
multipart parsing works
Browse files Browse the repository at this point in the history
  • Loading branch information
bytbox committed Apr 4, 2012
1 parent f7bb9a9 commit 1e1139a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
21 changes: 18 additions & 3 deletions multipart.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@
package mail

import (
"bytes"
"errors"
"io"
"io/ioutil"
"mime"
//"mime/multipart"
"mime/multipart"
)

type Part struct {
Type string
Data []byte
Headers map[string][]string
}

// Parse the body of a message, using the given content-type. If the content
Expand All @@ -21,12 +25,23 @@ func parseBody(ct string, body []byte) (parts []Part, err error) {
mt, ps, err := mime.ParseMediaType(ct)
if err != nil { return }
if mt != "multipart/alternative" {
parts = append(parts, Part{ct, body})
parts = append(parts, Part{ct, body, nil})
return
}
_, ok := ps["boundary"]
boundary, ok := ps["boundary"]
if !ok {
return nil, errors.New("multipart specified without boundary")
}
r := multipart.NewReader(bytes.NewReader(body), boundary)
p, err := r.NextPart()
for err == nil {
data, _ := ioutil.ReadAll(p) // ignore error
ct := p.Header["Content-Type"]

part := Part{ct[0], data, p.Header}
parts = append(parts, part)
p, err = r.NextPart()
}
if err == io.EOF { err = nil }
return
}
21 changes: 17 additions & 4 deletions multipart_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var parseBodyTests = []parseBodyTest{
ct: "text/plain",
body: []byte(`This is some text.`),
rps: []Part{
Part{"text/plain", []byte("This is some text.")},
Part{"text/plain", []byte("This is some text."), nil},
},
},
parseBodyTest{
Expand All @@ -35,11 +35,24 @@ Some other text.
rps: []Part{
Part{
"text/plain; charset=ISO-8859-1",
[]byte("Some text.\n"),
[]byte("Some text."),
map[string][]string{
"Content-Type": []string{
"text/plain; charset=ISO-8859-1",
},
},
},
Part{
"text/html; charset=ISO-8859-1",
[]byte("Some other text.\n"),
[]byte("Some other text."),
map[string][]string{
"Content-Type": []string{
"text/html; charset=ISO-8859-1",
},
"Content-Transfer-Encoding": []string{
"quoted-printable",
},
},
},
},
},
Expand All @@ -52,7 +65,7 @@ func TestParseBody(t *testing.T) {
t.Errorf("parseBody returned error for %#v: %#v", pt, e)
} else if !reflect.DeepEqual(parts, pt.rps) {
t.Errorf(
"parseBody: incorrect result for %#V: %#V vs. %#V",
"parseBody: incorrect result for %#V: \n%#V\nvs.\n%#V",
pt, parts, pt.rps)
}
}
Expand Down

0 comments on commit 1e1139a

Please sign in to comment.