Permalink
Browse files

multipart parsing works

  • Loading branch information...
1 parent f7bb9a9 commit 1e1139a44f499af23e23c099536dfeeaaffe306e @bytbox committed Apr 4, 2012
Showing with 35 additions and 7 deletions.
  1. +18 −3 multipart.go
  2. +17 −4 multipart_test.go
View
@@ -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
@@ -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
}
View
@@ -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{
@@ -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",
+ },
+ },
},
},
},
@@ -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)
}
}

0 comments on commit 1e1139a

Please sign in to comment.