blob: d526dd733563dc22ead4d510c9346e344734d3d3 [file] [log] [blame]
Dusan Kasan17e497e2017-04-10 22:44:22 +02001package parsemail
2
3import (
Dusan Kasan17e497e2017-04-10 22:44:22 +02004 "bytes"
Dusan Kasan4595dfe2017-04-13 00:38:24 +02005 "encoding/base64"
Dusan Kasan4595dfe2017-04-13 00:38:24 +02006 "fmt"
7 "io"
8 "io/ioutil"
9 "mime"
10 "mime/multipart"
11 "net/mail"
Edwin Love33953e52019-04-02 15:29:22 +010012 "regexp"
Dusan Kasan4595dfe2017-04-13 00:38:24 +020013 "strings"
14 "time"
Dusan Kasan17e497e2017-04-10 22:44:22 +020015)
16
Dusan Kasan45ca2642017-04-18 10:39:35 +020017const contentTypeMultipartMixed = "multipart/mixed"
18const contentTypeMultipartAlternative = "multipart/alternative"
19const contentTypeMultipartRelated = "multipart/related"
20const contentTypeTextHtml = "text/html"
21const contentTypeTextPlain = "text/plain"
Dusan Kasan17e497e2017-04-10 22:44:22 +020022
Dusan Kasan45ca2642017-04-18 10:39:35 +020023// Parse an email message read from io.Reader into parsemail.Email struct
Dusan Kasanb49ceb62017-04-13 00:00:36 +020024func Parse(r io.Reader) (email Email, err error) {
Dusan Kasan4595dfe2017-04-13 00:38:24 +020025 msg, err := mail.ReadMessage(r)
Dusan Kasan17e497e2017-04-10 22:44:22 +020026 if err != nil {
Dusan Kasanb49ceb62017-04-13 00:00:36 +020027 return
Dusan Kasan17e497e2017-04-10 22:44:22 +020028 }
29
Dusan Kasanb49ceb62017-04-13 00:00:36 +020030 email, err = createEmailFromHeader(msg.Header)
Dusan Kasan17e497e2017-04-10 22:44:22 +020031 if err != nil {
Dusan Kasanb49ceb62017-04-13 00:00:36 +020032 return
Dusan Kasan17e497e2017-04-10 22:44:22 +020033 }
34
Dusan Kasanb49ceb62017-04-13 00:00:36 +020035 contentType, params, err := parseContentType(msg.Header.Get("Content-Type"))
Dusan Kasan17e497e2017-04-10 22:44:22 +020036 if err != nil {
Dusan Kasanb49ceb62017-04-13 00:00:36 +020037 return
Dusan Kasan17e497e2017-04-10 22:44:22 +020038 }
39
Dusan Kasanb49ceb62017-04-13 00:00:36 +020040 switch contentType {
Dusan Kasan45ca2642017-04-18 10:39:35 +020041 case contentTypeMultipartMixed:
Dusan Kasan17e497e2017-04-10 22:44:22 +020042 email.TextBody, email.HTMLBody, email.Attachments, email.EmbeddedFiles, err = parseMultipartMixed(msg.Body, params["boundary"])
Dusan Kasan45ca2642017-04-18 10:39:35 +020043 case contentTypeMultipartAlternative:
Dusan Kasan17e497e2017-04-10 22:44:22 +020044 email.TextBody, email.HTMLBody, email.EmbeddedFiles, err = parseMultipartAlternative(msg.Body, params["boundary"])
Dusan Kasan45ca2642017-04-18 10:39:35 +020045 case contentTypeTextPlain:
Dusan Kasan17e497e2017-04-10 22:44:22 +020046 message, _ := ioutil.ReadAll(msg.Body)
47 email.TextBody = strings.TrimSuffix(string(message[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +020048 case contentTypeTextHtml:
Dusan Kasan17e497e2017-04-10 22:44:22 +020049 message, _ := ioutil.ReadAll(msg.Body)
50 email.HTMLBody = strings.TrimSuffix(string(message[:]), "\n")
Dusan Kasanb49ceb62017-04-13 00:00:36 +020051 default:
Dusan Kasan45ca2642017-04-18 10:39:35 +020052 err = fmt.Errorf("Unknown top level mime type: %s", contentType)
Dusan Kasan17e497e2017-04-10 22:44:22 +020053 }
54
Dusan Kasanb49ceb62017-04-13 00:00:36 +020055 return
56}
57
58func createEmailFromHeader(header mail.Header) (email Email, err error) {
Dusan Kasane668cf22017-04-18 12:56:51 +020059 hp := headerParser{header: &header}
60
Dusan Kasanf4376a62017-05-23 21:03:55 +020061 email.Subject = decodeMimeSentence(header.Get("Subject"))
Dusan Kasane668cf22017-04-18 12:56:51 +020062 email.From = hp.parseAddressList(header.Get("From"))
63 email.Sender = hp.parseAddress(header.Get("Sender"))
64 email.ReplyTo = hp.parseAddressList(header.Get("Reply-To"))
65 email.To = hp.parseAddressList(header.Get("To"))
66 email.Cc = hp.parseAddressList(header.Get("Cc"))
67 email.Bcc = hp.parseAddressList(header.Get("Bcc"))
68 email.Date = hp.parseTime(header.Get("Date"))
69 email.ResentFrom = hp.parseAddressList(header.Get("Resent-From"))
70 email.ResentSender = hp.parseAddress(header.Get("Resent-Sender"))
71 email.ResentTo = hp.parseAddressList(header.Get("Resent-To"))
72 email.ResentCc = hp.parseAddressList(header.Get("Resent-Cc"))
73 email.ResentBcc = hp.parseAddressList(header.Get("Resent-Bcc"))
74 email.ResentMessageID = hp.parseMessageId(header.Get("Resent-Message-ID"))
75 email.MessageID = hp.parseMessageId(header.Get("Message-ID"))
76 email.InReplyTo = hp.parseMessageIdList(header.Get("In-Reply-To"))
77 email.References = hp.parseMessageIdList(header.Get("References"))
78 email.ResentDate = hp.parseTime(header.Get("Resent-Date"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +020079
Dusan Kasane668cf22017-04-18 12:56:51 +020080 if hp.err != nil {
81 err = hp.err
Dusan Kasanb49ceb62017-04-13 00:00:36 +020082 return
83 }
84
Dusan Kasanb49ceb62017-04-13 00:00:36 +020085 //decode whole header for easier access to extra fields
86 //todo: should we decode? aren't only standard fields mime encoded?
87 email.Header, err = decodeHeaderMime(header)
88 if err != nil {
89 return
90 }
91
92 return
93}
94
95func parseContentType(contentTypeHeader string) (contentType string, params map[string]string, err error) {
96 if contentTypeHeader == "" {
Dusan Kasan45ca2642017-04-18 10:39:35 +020097 contentType = contentTypeTextPlain
Dusan Kasanb49ceb62017-04-13 00:00:36 +020098 return
99 }
100
101 return mime.ParseMediaType(contentTypeHeader)
102}
103
Kevin Chen5dc5bc82018-05-03 22:07:35 -0400104func parseMultipartRelated(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
105 pmr := multipart.NewReader(msg, boundary)
106 for {
107 part, err := pmr.NextPart()
108
109 if err == io.EOF {
110 break
111 } else if err != nil {
112 return textBody, htmlBody, embeddedFiles, err
113 }
114
115 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
116 if err != nil {
117 return textBody, htmlBody, embeddedFiles, err
118 }
119
120 switch contentType {
121 case contentTypeTextPlain:
122 ppContent, err := ioutil.ReadAll(part)
123 if err != nil {
124 return textBody, htmlBody, embeddedFiles, err
125 }
126
127 textBody += strings.TrimSuffix(string(ppContent[:]), "\n")
128 case contentTypeTextHtml:
129 ppContent, err := ioutil.ReadAll(part)
130 if err != nil {
131 return textBody, htmlBody, embeddedFiles, err
132 }
133
134 htmlBody += strings.TrimSuffix(string(ppContent[:]), "\n")
135 case contentTypeMultipartAlternative:
136 tb, hb, ef, err := parseMultipartAlternative(part, params["boundary"])
137 if err != nil {
138 return textBody, htmlBody, embeddedFiles, err
139 }
140
141 htmlBody += hb
142 textBody += tb
143 embeddedFiles = append(embeddedFiles, ef...)
144 default:
145 if isEmbeddedFile(part) {
146 ef, err := decodeEmbeddedFile(part)
147 if err != nil {
148 return textBody, htmlBody, embeddedFiles, err
149 }
150
151 embeddedFiles = append(embeddedFiles, ef)
152 } else {
153 return textBody, htmlBody, embeddedFiles, fmt.Errorf("Can't process multipart/related inner mime type: %s", contentType)
154 }
155 }
156 }
157
158 return textBody, htmlBody, embeddedFiles, err
159}
160
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200161func parseMultipartAlternative(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
162 pmr := multipart.NewReader(msg, boundary)
163 for {
164 part, err := pmr.NextPart()
165
166 if err == io.EOF {
167 break
168 } else if err != nil {
169 return textBody, htmlBody, embeddedFiles, err
170 }
171
172 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
Dusan Kasanc661cc02017-04-18 10:51:51 +0200173 if err != nil {
174 return textBody, htmlBody, embeddedFiles, err
175 }
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200176
177 switch contentType {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200178 case contentTypeTextPlain:
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200179 ppContent, err := ioutil.ReadAll(part)
180 if err != nil {
181 return textBody, htmlBody, embeddedFiles, err
182 }
183
184 textBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +0200185 case contentTypeTextHtml:
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200186 ppContent, err := ioutil.ReadAll(part)
187 if err != nil {
188 return textBody, htmlBody, embeddedFiles, err
189 }
190
191 htmlBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +0200192 case contentTypeMultipartRelated:
Kevin Chen9b9506a2018-05-03 22:17:38 -0400193 tb, hb, ef, err := parseMultipartRelated(part, params["boundary"])
Dusan Kasan1a966482017-04-18 10:45:25 +0200194 if err != nil {
195 return textBody, htmlBody, embeddedFiles, err
196 }
197
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200198 htmlBody += hb
199 textBody += tb
200 embeddedFiles = append(embeddedFiles, ef...)
201 default:
202 if isEmbeddedFile(part) {
203 ef, err := decodeEmbeddedFile(part)
204 if err != nil {
205 return textBody, htmlBody, embeddedFiles, err
206 }
207
208 embeddedFiles = append(embeddedFiles, ef)
209 } else {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200210 return textBody, htmlBody, embeddedFiles, fmt.Errorf("Can't process multipart/alternative inner mime type: %s", contentType)
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200211 }
212 }
213 }
214
215 return textBody, htmlBody, embeddedFiles, err
216}
217
218func parseMultipartMixed(msg io.Reader, boundary string) (textBody, htmlBody string, attachments []Attachment, embeddedFiles []EmbeddedFile, err error) {
219 mr := multipart.NewReader(msg, boundary)
220 for {
221 part, err := mr.NextPart()
222 if err == io.EOF {
223 break
224 } else if err != nil {
225 return textBody, htmlBody, attachments, embeddedFiles, err
226 }
227
228 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
229 if err != nil {
230 return textBody, htmlBody, attachments, embeddedFiles, err
231 }
232
Dusan Kasan45ca2642017-04-18 10:39:35 +0200233 if contentType == contentTypeMultipartAlternative {
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200234 textBody, htmlBody, embeddedFiles, err = parseMultipartAlternative(part, params["boundary"])
235 if err != nil {
236 return textBody, htmlBody, attachments, embeddedFiles, err
237 }
Kevin Chen5dc5bc82018-05-03 22:07:35 -0400238 } else if contentType == contentTypeMultipartRelated {
239 textBody, htmlBody, embeddedFiles, err = parseMultipartRelated(part, params["boundary"])
240 if err != nil {
241 return textBody, htmlBody, attachments, embeddedFiles, err
242 }
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200243 } else if isAttachment(part) {
244 at, err := decodeAttachment(part)
245 if err != nil {
246 return textBody, htmlBody, attachments, embeddedFiles, err
247 }
248
249 attachments = append(attachments, at)
250 } else {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200251 return textBody, htmlBody, attachments, embeddedFiles, fmt.Errorf("Unknown multipart/mixed nested mime type: %s", contentType)
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200252 }
253 }
254
255 return textBody, htmlBody, attachments, embeddedFiles, err
Dusan Kasan17e497e2017-04-10 22:44:22 +0200256}
257
Dusan Kasanf4376a62017-05-23 21:03:55 +0200258func decodeMimeSentence(s string) string {
Dusan Kasan17e497e2017-04-10 22:44:22 +0200259 result := []string{}
260 ss := strings.Split(s, " ")
261
262 for _, word := range ss {
263 dec := new(mime.WordDecoder)
264 w, err := dec.Decode(word)
265 if err != nil {
266 if len(result) == 0 {
267 w = word
268 } else {
269 w = " " + word
270 }
271 }
272
273 result = append(result, w)
274 }
275
Dusan Kasanf4376a62017-05-23 21:03:55 +0200276 return strings.Join(result, "")
Dusan Kasan17e497e2017-04-10 22:44:22 +0200277}
278
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200279func decodeHeaderMime(header mail.Header) (mail.Header, error) {
Dusan Kasan17e497e2017-04-10 22:44:22 +0200280 parsedHeader := map[string][]string{}
281
282 for headerName, headerData := range header {
283
284 parsedHeaderData := []string{}
285 for _, headerValue := range headerData {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200286 parsedHeaderData = append(parsedHeaderData, decodeMimeSentence(headerValue))
Dusan Kasan17e497e2017-04-10 22:44:22 +0200287 }
288
289 parsedHeader[headerName] = parsedHeaderData
290 }
291
292 return mail.Header(parsedHeader), nil
293}
294
295func decodePartData(part *multipart.Part) (io.Reader, error) {
296 encoding := part.Header.Get("Content-Transfer-Encoding")
297
Kevin Chen7835eb02018-05-02 20:58:58 -0400298 if strings.EqualFold(encoding, "base64") {
Dusan Kasan17e497e2017-04-10 22:44:22 +0200299 dr := base64.NewDecoder(base64.StdEncoding, part)
300 dd, err := ioutil.ReadAll(dr)
301 if err != nil {
302 return nil, err
303 }
304
305 return bytes.NewReader(dd), nil
Dusan Kasan17e497e2017-04-10 22:44:22 +0200306 }
Dusan Kasan45ca2642017-04-18 10:39:35 +0200307
308 return nil, fmt.Errorf("Unknown encoding: %s", encoding)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200309}
310
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200311func isEmbeddedFile(part *multipart.Part) bool {
312 return part.Header.Get("Content-Transfer-Encoding") != ""
313}
314
315func decodeEmbeddedFile(part *multipart.Part) (ef EmbeddedFile, err error) {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200316 cid := decodeMimeSentence(part.Header.Get("Content-Id"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200317 decoded, err := decodePartData(part)
318 if err != nil {
319 return
320 }
321
322 ef.CID = strings.Trim(cid, "<>")
323 ef.Data = decoded
324 ef.ContentType = part.Header.Get("Content-Type")
325
326 return
327}
328
329func isAttachment(part *multipart.Part) bool {
330 return part.FileName() != ""
331}
332
333func decodeAttachment(part *multipart.Part) (at Attachment, err error) {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200334 filename := decodeMimeSentence(part.FileName())
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200335 decoded, err := decodePartData(part)
336 if err != nil {
337 return
338 }
339
340 at.Filename = filename
341 at.Data = decoded
342 at.ContentType = strings.Split(part.Header.Get("Content-Type"), ";")[0]
343
344 return
345}
346
Dusan Kasane668cf22017-04-18 12:56:51 +0200347type headerParser struct {
348 header *mail.Header
Dusan Kasanb974c632017-04-18 12:58:42 +0200349 err error
Dusan Kasane668cf22017-04-18 12:56:51 +0200350}
351
352func (hp headerParser) parseAddress(s string) (ma *mail.Address) {
353 if hp.err != nil {
354 return nil
355 }
356
357 if strings.Trim(s, " \n") != "" {
358 ma, hp.err = mail.ParseAddress(s)
359
360 return ma
361 }
362
363 return nil
364}
365
366func (hp headerParser) parseAddressList(s string) (ma []*mail.Address) {
367 if hp.err != nil {
368 return
369 }
370
371 if strings.Trim(s, " \n") != "" {
372 ma, hp.err = mail.ParseAddressList(s)
373 return
374 }
375
376 return
377}
378
Edwin Love33953e52019-04-02 15:29:22 +0100379var timezoneRegex = regexp.MustCompile(` \([A-Za-z0-9]+\)$`)
380
Dusan Kasane668cf22017-04-18 12:56:51 +0200381func (hp headerParser) parseTime(s string) (t time.Time) {
Dusan Kasanb974c632017-04-18 12:58:42 +0200382 if hp.err != nil || s == "" {
Dusan Kasane668cf22017-04-18 12:56:51 +0200383 return
384 }
385
386 t, hp.err = time.Parse(time.RFC1123Z, s)
387 if hp.err == nil {
388 return t
389 }
390
Edwin Love33953e52019-04-02 15:29:22 +0100391 s = timezoneRegex.ReplaceAllString(s, "")
392
Dusan Kasane668cf22017-04-18 12:56:51 +0200393 t, hp.err = time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", s)
394
395 return
396}
397
398func (hp headerParser) parseMessageId(s string) string {
399 if hp.err != nil {
400 return ""
401 }
402
403 return strings.Trim(s, "<> ")
404}
405
406func (hp headerParser) parseMessageIdList(s string) (result []string) {
407 if hp.err != nil {
408 return
409 }
410
411 for _, p := range strings.Split(s, " ") {
412 if strings.Trim(p, " \n") != "" {
413 result = append(result, hp.parseMessageId(p))
414 }
415 }
416
417 return
418}
419
Dusan Kasan1a966482017-04-18 10:45:25 +0200420// Attachment with filename, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200421type Attachment struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200422 Filename string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200423 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200424 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200425}
426
Dusan Kasan1a966482017-04-18 10:45:25 +0200427// EmbeddedFile with content id, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200428type EmbeddedFile struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200429 CID string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200430 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200431 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200432}
433
Dusan Kasan1a966482017-04-18 10:45:25 +0200434// Email with fields for all the headers defined in RFC5322 with it's attachments and
Dusan Kasan17e497e2017-04-10 22:44:22 +0200435type Email struct {
436 Header mail.Header
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200437
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200438 Subject string
439 Sender *mail.Address
440 From []*mail.Address
441 ReplyTo []*mail.Address
442 To []*mail.Address
443 Cc []*mail.Address
444 Bcc []*mail.Address
445 Date time.Time
446 MessageID string
447 InReplyTo []string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200448 References []string
449
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200450 ResentFrom []*mail.Address
451 ResentSender *mail.Address
452 ResentTo []*mail.Address
453 ResentDate time.Time
454 ResentCc []*mail.Address
455 ResentBcc []*mail.Address
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200456 ResentMessageID string
457
Dusan Kasan17e497e2017-04-10 22:44:22 +0200458 HTMLBody string
459 TextBody string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200460
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200461 Attachments []Attachment
Dusan Kasan17e497e2017-04-10 22:44:22 +0200462 EmbeddedFiles []EmbeddedFile
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200463}