/
parse.go
65 lines (55 loc) · 1.35 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package maildir
import (
"encoding/base64"
"io"
"io/ioutil"
"log"
"mime"
"mime/multipart"
"mime/quotedprintable"
"net/mail"
"strings"
)
type header interface {
Get(string) string
}
// Parses multipart and quoted-printable mail bodies.
func parseBody(msg *mail.Message) (body Body, err error) {
mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
if err != nil {
log.Println("[ERROR] maildir:", err)
}
if strings.HasPrefix(mediaType, "multipart/") {
mr := multipart.NewReader(msg.Body, params["boundary"])
for {
p, err := mr.NextPart()
if err != nil {
break
}
decodePart(p.Header, p, &body)
}
} else {
decodePart(msg.Header, msg.Body, &body)
}
return
}
func decodePart(h header, body io.Reader, out *Body) {
var raw []byte
var err error
if strings.ToLower(h.Get("Content-Transfer-Encoding")) == "quoted-printable" {
raw, err = ioutil.ReadAll(quotedprintable.NewReader(body))
} else if strings.ToLower(h.Get("Content-Transfer-Encoding")) == "base64" {
raw, err = ioutil.ReadAll(base64.NewDecoder(base64.StdEncoding, body))
} else {
raw, err = ioutil.ReadAll(body)
}
contentType, _, err := mime.ParseMediaType(h.Get("Content-Type"))
if err != nil {
log.Println("[ERROR] maildir:", err)
}
if contentType == "text/html" {
out.HTML = string(raw)
} else {
out.Plain = string(raw)
}
}