forked from sorbits/go.enmime
/
mail.go
336 lines (298 loc) · 9.29 KB
/
mail.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package enmime
import (
"fmt"
"mime"
"net/mail"
"net/textproto"
"strings"
)
// MIMEBody is the outer wrapper for MIME messages.
type MIMEBody struct {
Text string // The plain text portion of the message
Html string // The HTML portion of the message
Root MIMEPart // The top-level MIMEPart
Attachments []MIMEPart // All parts having a Content-Disposition of attachment
Inlines []MIMEPart // All parts having a Content-Disposition of inline
OtherParts []MIMEPart // All parts not in Attachments and Inlines
header mail.Header // Header from original message
}
var AddressHeaders = []string{"From", "To", "Delivered-To", "Cc", "Bcc", "Reply-To"}
// IsMultipartMessage returns true if the message has a recognized multipart Content-Type
// header. You don't need to check this before calling ParseMIMEBody, it can handle
// non-multipart messages.
func IsMultipartMessage(mailMsg *mail.Message) bool {
// Parse top-level multipart
ctype := mailMsg.Header.Get("Content-Type")
mediatype, _, err := mime.ParseMediaType(ctype)
if err != nil {
return false
}
switch mediatype {
case "multipart/alternative",
"multipart/mixed",
"multipart/related",
"multipart/signed":
return true
default:
if strings.HasPrefix(mediatype, "multipart/") {
// according to rfc2046#section-5.1.7 all other multipart should
// be treated as multipart/mixed
return true
}
}
return false
}
// IsAttachment returns true, if the given header defines an attachment.
// First it checks, if the Content-Disposition header defines an attachement.
// If this test is false, the Content-Type header is checked.
//
// Valid Attachment-Headers:
//
// Content-Disposition: attachment; filename="frog.jpg"
// Content-Type: attachment; filename="frog.jpg"
//
func IsAttachment(header mail.Header) bool {
mediatype, _, _ := mime.ParseMediaType(header.Get("Content-Disposition"))
if strings.ToLower(mediatype) == "attachment" {
return true
}
mediatype, _, _ = mime.ParseMediaType(header.Get("Content-Type"))
if strings.ToLower(mediatype) == "attachment" {
return true
}
return false
}
// IsPlain returns true, if the the mime headers define a valid
// 'text/plain' or 'text/html part'. Ff emptyContentTypeIsPlain is set
// to true, a missing Content-Type header will result in a positive
// plain part detection.
func IsPlain(header mail.Header, emptyContentTypeIsPlain bool) bool {
ctype := header.Get("Content-Type")
if ctype == "" && emptyContentTypeIsPlain {
return true
}
mediatype, _, err := mime.ParseMediaType(ctype)
if err != nil {
return false
}
switch mediatype {
case "text/plain",
"text/html":
return true
}
return false
}
// IsBinaryBody returns true, if the mail header defines a binary body.
func IsBinaryBody(mailMsg *mail.Message) bool {
if IsAttachment(mailMsg.Header) == true {
return true
}
return !IsPlain(mailMsg.Header, true)
}
// Returns a MIME message with only one Attachment, the parsed original mail body.
func binMIME(mailMsg *mail.Message) (*MIMEBody, error) {
// Root Node of our tree
ctype := mailMsg.Header.Get("Content-Type")
mediatype, mparams, err := mime.ParseMediaType(ctype)
if err != nil {
mediatype = "attachment"
}
m := &MIMEBody{
header: mailMsg.Header,
Root: NewMIMEPart(nil, mediatype),
}
p := NewMIMEPart(nil, mediatype)
p.content, err = decodeSection(mailMsg.Header.Get("Content-Transfer-Encoding"), mailMsg.Body)
if err != nil {
return nil, err
}
// get set headers
p.header = make(textproto.MIMEHeader, 4)
// Figure out our disposition, filename
disposition, dparams, err := mime.ParseMediaType(mailMsg.Header.Get("Content-Disposition"))
if err == nil {
// Disposition is optional
p.disposition = disposition
p.fileName = DecodeHeader(dparams["filename"])
}
if p.fileName == "" && mparams["name"] != "" {
p.fileName = DecodeHeader(mparams["name"])
}
if p.fileName == "" && mparams["file"] != "" {
p.fileName = DecodeHeader(mparams["file"])
}
if p.charset == "" {
p.charset = mparams["charset"]
}
p.header.Set("Content-Type", mailMsg.Header.Get("Content-Type"))
p.header.Set("Content-Disposition", mailMsg.Header.Get("Content-Disposition"))
m.Attachments = append(m.Attachments, p)
return m, err
}
// ParseMIMEBody parses the body of the message object into a tree of MIMEPart objects,
// each of which is aware of its content type, filename and headers. If the part was
// encoded in quoted-printable or base64, it is decoded before being stored in the
// MIMEPart object.
func ParseMIMEBody(mailMsg *mail.Message) (*MIMEBody, error) {
mimeMsg := &MIMEBody{header: mailMsg.Header}
if !IsMultipartMessage(mailMsg) {
// Attachment only?
if IsBinaryBody(mailMsg) {
return binMIME(mailMsg)
}
// Parse as text only
bodyBytes, err := decodeSection(mailMsg.Header.Get("Content-Transfer-Encoding"),
mailMsg.Body)
if err != nil {
return nil, fmt.Errorf("Error decoding text-only message: %v", err)
}
mimeMsg.Text = string(bodyBytes)
// Check for HTML at top-level, eat errors quietly
ctype := mailMsg.Header.Get("Content-Type")
if ctype != "" {
if mediatype, mparams, err := mime.ParseMediaType(ctype); err == nil {
/*
*Content-Type: text/plain;\t charset="hz-gb-2312"
*/
if mparams["charset"] != "" {
newStr, err := ConvertToUTF8String(mparams["charset"], bodyBytes)
if err != nil {
return nil, err
}
mimeMsg.Text = newStr
} else if mediatype == "text/html" { // charset is empty, look in html body for charset
charset, err := charsetFromHTMLString(mimeMsg.Text)
if charset != "" && err == nil {
newStr, err := ConvertToUTF8String(charset, bodyBytes)
if err == nil {
mimeMsg.Text = newStr
}
}
}
if mediatype == "text/html" {
mimeMsg.Html = mimeMsg.Text
}
}
}
} else {
// Parse top-level multipart
ctype := mailMsg.Header.Get("Content-Type")
mediatype, params, err := mime.ParseMediaType(ctype)
if err != nil {
return nil, fmt.Errorf("Unable to parse media type: %v", err)
}
if !strings.HasPrefix(mediatype, "multipart/") {
return nil, fmt.Errorf("Unknown mediatype: %v", mediatype)
}
boundary := params["boundary"]
if boundary == "" {
return nil, fmt.Errorf("Unable to locate boundary param in Content-Type header")
}
// Root Node of our tree
root := NewMIMEPart(nil, mediatype)
mimeMsg.Root = root
err = parseParts(root, mailMsg.Body, boundary)
if err != nil {
return nil, err
}
// Locate text body
if mediatype == "multipart/altern" {
match := BreadthMatchFirst(root, func(p MIMEPart) bool {
return p.ContentType() == "text/plain" && p.Disposition() != "attachment"
})
if match != nil {
if match.Charset() != "" {
newStr, err := ConvertToUTF8String(match.Charset(), match.Content())
if err != nil {
return nil, err
}
mimeMsg.Text += newStr
} else {
mimeMsg.Text += string(match.Content())
}
}
} else {
// multipart is of a mixed type
match := DepthMatchAll(root, func(p MIMEPart) bool {
return p.ContentType() == "text/plain" && p.Disposition() != "attachment"
})
for i, m := range match {
if i > 0 {
mimeMsg.Text += "\n--\n"
}
if m.Charset() != "" {
newStr, err := ConvertToUTF8String(m.Charset(), m.Content())
if err != nil {
return nil, err
}
mimeMsg.Text += newStr
} else {
mimeMsg.Text += string(m.Content())
}
}
}
// Locate HTML body
match := BreadthMatchFirst(root, func(p MIMEPart) bool {
return p.ContentType() == "text/html" && p.Disposition() != "attachment"
})
if match != nil {
if match.Charset() != "" {
newStr, err := ConvertToUTF8String(match.Charset(), match.Content())
if err != nil {
return nil, err
}
mimeMsg.Html += newStr
} else {
mimeMsg.Html = string(match.Content())
}
}
// Locate attachments
mimeMsg.Attachments = BreadthMatchAll(root, func(p MIMEPart) bool {
return p.Disposition() == "attachment" || p.ContentType() == "application/octet-stream"
})
// Locate inlines
mimeMsg.Inlines = BreadthMatchAll(root, func(p MIMEPart) bool {
return p.Disposition() == "inline"
})
// Locate others parts not handled in "Attachments" and "inlines"
mimeMsg.OtherParts = BreadthMatchAll(root, func(p MIMEPart) bool {
if strings.HasPrefix(p.ContentType(), "multipart/") {
return false
}
if p.Disposition() != "" {
return false
}
if p.ContentType() == "application/octet-stream" {
return false
}
return p.ContentType() != "text/plain" && p.ContentType() != "text/html"
})
}
return mimeMsg, nil
}
// Process the specified header for RFC 2047 encoded words and return the result
func (m *MIMEBody) GetHeader(name string) string {
return DecodeHeader(m.header.Get(name))
}
// Return AddressList with RFC 2047 encoded encoded names.
func (m *MIMEBody) AddressList(key string) ([]*mail.Address, error) {
isAddrHeader := false
for _, hkey := range AddressHeaders {
if strings.ToLower(hkey) == strings.ToLower(key) {
isAddrHeader = true
break
}
}
if !isAddrHeader {
return nil, fmt.Errorf("%s is not address header", key)
}
str := DecodeToUTF8Base64Header(m.header.Get(key))
if str == "" {
return nil, mail.ErrHeaderNotPresent
}
ret, err := mail.ParseAddressList(str)
if err != nil {
return nil, err
}
return ret, nil
}