diff --git a/message.go b/message.go index d7b5a81..3f28a81 100644 --- a/message.go +++ b/message.go @@ -4,7 +4,7 @@ import ( "crypto/rand" "encoding/base64" "log" - "regexp" + "mime" "strings" "time" ) @@ -116,14 +116,14 @@ func (content *Content) ParseMIMEBody() *MIMEBody { if hdr, ok := content.Headers["Content-Type"]; ok { if len(hdr) > 0 { - re := regexp.MustCompile("boundary=\"([^\"]+)\"") - match := re.FindStringSubmatch(hdr[0]) - if len(match) < 2 { + boundary := extractBoundary(hdr[0]) + var p []string + if len(boundary) > 0 { + p = strings.Split(content.Body, "--"+boundary) + log.Printf("Got boundary: %s", boundary) + } else { log.Printf("Boundary not found: %s", hdr[0]) } - log.Printf("Got boundary: %s", match[1]) - - p := strings.Split(content.Body, "--"+match[1]) for _, s := range p { if len(s) > 0 { @@ -204,3 +204,13 @@ func ContentFromString(data string) *Content { Body: x[0], } } + +// extractBoundary extract boundary string in contentType. +// It returns empty string if no valid boundary found +func extractBoundary(contentType string) string { + _, params, err := mime.ParseMediaType(contentType) + if err == nil { + return params["boundary"] + } + return "" +} diff --git a/message_test.go b/message_test.go new file mode 100644 index 0000000..32794a7 --- /dev/null +++ b/message_test.go @@ -0,0 +1,27 @@ +package data + +import ( + "testing" +) + +func TestExtractBoundary(t *testing.T) { + contents := []struct { + content string + expect string + }{ + { + `multipart/alternative; boundary="_----------=_MCPart_498914860"`, + `_----------=_MCPart_498914860`, + }, + { + `multipart/alternative; boundary=047d7bd74a2049b624050d805118`, + `047d7bd74a2049b624050d805118`, + }, + } + + for _, c := range contents { + if b := extractBoundary(c.content); b != c.expect { + t.Fatal("extractBoundary expect", c.expect, "but get", b) + } + } +}