blob: 42e01709603ecbe1913216075685f5385c193d79 [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"
12 "strings"
13 "time"
Dusan Kasan17e497e2017-04-10 22:44:22 +020014)
15
Dusan Kasan45ca2642017-04-18 10:39:35 +020016const contentTypeMultipartMixed = "multipart/mixed"
17const contentTypeMultipartAlternative = "multipart/alternative"
18const contentTypeMultipartRelated = "multipart/related"
19const contentTypeTextHtml = "text/html"
20const contentTypeTextPlain = "text/plain"
Dusan Kasan17e497e2017-04-10 22:44:22 +020021
Dusan Kasan45ca2642017-04-18 10:39:35 +020022// Parse an email message read from io.Reader into parsemail.Email struct
Dusan Kasanb49ceb62017-04-13 00:00:36 +020023func Parse(r io.Reader) (email Email, err error) {
Dusan Kasan4595dfe2017-04-13 00:38:24 +020024 msg, err := mail.ReadMessage(r)
Dusan Kasan17e497e2017-04-10 22:44:22 +020025 if err != nil {
Dusan Kasanb49ceb62017-04-13 00:00:36 +020026 return
Dusan Kasan17e497e2017-04-10 22:44:22 +020027 }
28
Dusan Kasanb49ceb62017-04-13 00:00:36 +020029 email, err = createEmailFromHeader(msg.Header)
Dusan Kasan17e497e2017-04-10 22:44:22 +020030 if err != nil {
Dusan Kasanb49ceb62017-04-13 00:00:36 +020031 return
Dusan Kasan17e497e2017-04-10 22:44:22 +020032 }
33
Dusan Kasan428369f2020-02-24 00:47:31 +010034 email.ContentType = msg.Header.Get("Content-Type")
35 contentType, params, err := parseContentType(email.ContentType)
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"])
Obi Symons89230f42020-04-04 14:32:11 +110045 case contentTypeMultipartRelated:
46 email.TextBody, email.HTMLBody, email.EmbeddedFiles, err = parseMultipartRelated(msg.Body, params["boundary"])
Dusan Kasan45ca2642017-04-18 10:39:35 +020047 case contentTypeTextPlain:
Dusan Kasan17e497e2017-04-10 22:44:22 +020048 message, _ := ioutil.ReadAll(msg.Body)
49 email.TextBody = strings.TrimSuffix(string(message[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +020050 case contentTypeTextHtml:
Dusan Kasan17e497e2017-04-10 22:44:22 +020051 message, _ := ioutil.ReadAll(msg.Body)
52 email.HTMLBody = strings.TrimSuffix(string(message[:]), "\n")
Dusan Kasanb49ceb62017-04-13 00:00:36 +020053 default:
Dusan Kasan428369f2020-02-24 00:47:31 +010054 email.Content, err = decodeContent(msg.Body, msg.Header.Get("Content-Transfer-Encoding"))
Dusan Kasan17e497e2017-04-10 22:44:22 +020055 }
56
Dusan Kasanb49ceb62017-04-13 00:00:36 +020057 return
58}
59
60func createEmailFromHeader(header mail.Header) (email Email, err error) {
Dusan Kasane668cf22017-04-18 12:56:51 +020061 hp := headerParser{header: &header}
62
Dusan Kasanf4376a62017-05-23 21:03:55 +020063 email.Subject = decodeMimeSentence(header.Get("Subject"))
Dusan Kasane668cf22017-04-18 12:56:51 +020064 email.From = hp.parseAddressList(header.Get("From"))
65 email.Sender = hp.parseAddress(header.Get("Sender"))
66 email.ReplyTo = hp.parseAddressList(header.Get("Reply-To"))
67 email.To = hp.parseAddressList(header.Get("To"))
68 email.Cc = hp.parseAddressList(header.Get("Cc"))
69 email.Bcc = hp.parseAddressList(header.Get("Bcc"))
70 email.Date = hp.parseTime(header.Get("Date"))
71 email.ResentFrom = hp.parseAddressList(header.Get("Resent-From"))
72 email.ResentSender = hp.parseAddress(header.Get("Resent-Sender"))
73 email.ResentTo = hp.parseAddressList(header.Get("Resent-To"))
74 email.ResentCc = hp.parseAddressList(header.Get("Resent-Cc"))
75 email.ResentBcc = hp.parseAddressList(header.Get("Resent-Bcc"))
76 email.ResentMessageID = hp.parseMessageId(header.Get("Resent-Message-ID"))
77 email.MessageID = hp.parseMessageId(header.Get("Message-ID"))
78 email.InReplyTo = hp.parseMessageIdList(header.Get("In-Reply-To"))
79 email.References = hp.parseMessageIdList(header.Get("References"))
80 email.ResentDate = hp.parseTime(header.Get("Resent-Date"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +020081
Dusan Kasane668cf22017-04-18 12:56:51 +020082 if hp.err != nil {
83 err = hp.err
Dusan Kasanb49ceb62017-04-13 00:00:36 +020084 return
85 }
86
Dusan Kasanb49ceb62017-04-13 00:00:36 +020087 //decode whole header for easier access to extra fields
88 //todo: should we decode? aren't only standard fields mime encoded?
89 email.Header, err = decodeHeaderMime(header)
90 if err != nil {
91 return
92 }
93
94 return
95}
96
97func parseContentType(contentTypeHeader string) (contentType string, params map[string]string, err error) {
98 if contentTypeHeader == "" {
Dusan Kasan45ca2642017-04-18 10:39:35 +020099 contentType = contentTypeTextPlain
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200100 return
101 }
102
103 return mime.ParseMediaType(contentTypeHeader)
104}
105
Kevin Chen5dc5bc82018-05-03 22:07:35 -0400106func parseMultipartRelated(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
107 pmr := multipart.NewReader(msg, boundary)
108 for {
109 part, err := pmr.NextPart()
110
111 if err == io.EOF {
112 break
113 } else if err != nil {
114 return textBody, htmlBody, embeddedFiles, err
115 }
116
117 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
118 if err != nil {
119 return textBody, htmlBody, embeddedFiles, err
120 }
121
122 switch contentType {
123 case contentTypeTextPlain:
124 ppContent, err := ioutil.ReadAll(part)
125 if err != nil {
126 return textBody, htmlBody, embeddedFiles, err
127 }
128
129 textBody += strings.TrimSuffix(string(ppContent[:]), "\n")
130 case contentTypeTextHtml:
131 ppContent, err := ioutil.ReadAll(part)
132 if err != nil {
133 return textBody, htmlBody, embeddedFiles, err
134 }
135
136 htmlBody += strings.TrimSuffix(string(ppContent[:]), "\n")
137 case contentTypeMultipartAlternative:
138 tb, hb, ef, err := parseMultipartAlternative(part, params["boundary"])
139 if err != nil {
140 return textBody, htmlBody, embeddedFiles, err
141 }
142
143 htmlBody += hb
144 textBody += tb
145 embeddedFiles = append(embeddedFiles, ef...)
146 default:
147 if isEmbeddedFile(part) {
148 ef, err := decodeEmbeddedFile(part)
149 if err != nil {
150 return textBody, htmlBody, embeddedFiles, err
151 }
152
153 embeddedFiles = append(embeddedFiles, ef)
154 } else {
155 return textBody, htmlBody, embeddedFiles, fmt.Errorf("Can't process multipart/related inner mime type: %s", contentType)
156 }
157 }
158 }
159
160 return textBody, htmlBody, embeddedFiles, err
161}
162
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200163func parseMultipartAlternative(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
164 pmr := multipart.NewReader(msg, boundary)
165 for {
166 part, err := pmr.NextPart()
167
168 if err == io.EOF {
169 break
170 } else if err != nil {
171 return textBody, htmlBody, embeddedFiles, err
172 }
173
174 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
Dusan Kasanc661cc02017-04-18 10:51:51 +0200175 if err != nil {
176 return textBody, htmlBody, embeddedFiles, err
177 }
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200178
179 switch contentType {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200180 case contentTypeTextPlain:
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200181 ppContent, err := ioutil.ReadAll(part)
182 if err != nil {
183 return textBody, htmlBody, embeddedFiles, err
184 }
185
186 textBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +0200187 case contentTypeTextHtml:
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200188 ppContent, err := ioutil.ReadAll(part)
189 if err != nil {
190 return textBody, htmlBody, embeddedFiles, err
191 }
192
193 htmlBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +0200194 case contentTypeMultipartRelated:
Kevin Chen9b9506a2018-05-03 22:17:38 -0400195 tb, hb, ef, err := parseMultipartRelated(part, params["boundary"])
Dusan Kasan1a966482017-04-18 10:45:25 +0200196 if err != nil {
197 return textBody, htmlBody, embeddedFiles, err
198 }
199
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200200 htmlBody += hb
201 textBody += tb
202 embeddedFiles = append(embeddedFiles, ef...)
203 default:
204 if isEmbeddedFile(part) {
205 ef, err := decodeEmbeddedFile(part)
206 if err != nil {
207 return textBody, htmlBody, embeddedFiles, err
208 }
209
210 embeddedFiles = append(embeddedFiles, ef)
211 } else {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200212 return textBody, htmlBody, embeddedFiles, fmt.Errorf("Can't process multipart/alternative inner mime type: %s", contentType)
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200213 }
214 }
215 }
216
217 return textBody, htmlBody, embeddedFiles, err
218}
219
220func parseMultipartMixed(msg io.Reader, boundary string) (textBody, htmlBody string, attachments []Attachment, embeddedFiles []EmbeddedFile, err error) {
221 mr := multipart.NewReader(msg, boundary)
222 for {
223 part, err := mr.NextPart()
224 if err == io.EOF {
225 break
226 } else if err != nil {
227 return textBody, htmlBody, attachments, embeddedFiles, err
228 }
229
230 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
231 if err != nil {
232 return textBody, htmlBody, attachments, embeddedFiles, err
233 }
234
Dusan Kasan45ca2642017-04-18 10:39:35 +0200235 if contentType == contentTypeMultipartAlternative {
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200236 textBody, htmlBody, embeddedFiles, err = parseMultipartAlternative(part, params["boundary"])
237 if err != nil {
238 return textBody, htmlBody, attachments, embeddedFiles, err
239 }
Kevin Chen5dc5bc82018-05-03 22:07:35 -0400240 } else if contentType == contentTypeMultipartRelated {
241 textBody, htmlBody, embeddedFiles, err = parseMultipartRelated(part, params["boundary"])
242 if err != nil {
243 return textBody, htmlBody, attachments, embeddedFiles, err
244 }
Maya Rashisha3803bd2019-06-08 17:53:21 +0300245 } else if contentType == contentTypeTextPlain {
246 ppContent, err := ioutil.ReadAll(part)
247 if err != nil {
248 return textBody, htmlBody, attachments, embeddedFiles, err
249 }
250
251 textBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200252 } else if isAttachment(part) {
253 at, err := decodeAttachment(part)
254 if err != nil {
255 return textBody, htmlBody, attachments, embeddedFiles, err
256 }
257
258 attachments = append(attachments, at)
259 } else {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200260 return textBody, htmlBody, attachments, embeddedFiles, fmt.Errorf("Unknown multipart/mixed nested mime type: %s", contentType)
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200261 }
262 }
263
264 return textBody, htmlBody, attachments, embeddedFiles, err
Dusan Kasan17e497e2017-04-10 22:44:22 +0200265}
266
Dusan Kasanf4376a62017-05-23 21:03:55 +0200267func decodeMimeSentence(s string) string {
Dusan Kasan17e497e2017-04-10 22:44:22 +0200268 result := []string{}
269 ss := strings.Split(s, " ")
270
271 for _, word := range ss {
272 dec := new(mime.WordDecoder)
273 w, err := dec.Decode(word)
274 if err != nil {
275 if len(result) == 0 {
276 w = word
277 } else {
278 w = " " + word
279 }
280 }
281
282 result = append(result, w)
283 }
284
Dusan Kasanf4376a62017-05-23 21:03:55 +0200285 return strings.Join(result, "")
Dusan Kasan17e497e2017-04-10 22:44:22 +0200286}
287
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200288func decodeHeaderMime(header mail.Header) (mail.Header, error) {
Dusan Kasan17e497e2017-04-10 22:44:22 +0200289 parsedHeader := map[string][]string{}
290
291 for headerName, headerData := range header {
292
293 parsedHeaderData := []string{}
294 for _, headerValue := range headerData {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200295 parsedHeaderData = append(parsedHeaderData, decodeMimeSentence(headerValue))
Dusan Kasan17e497e2017-04-10 22:44:22 +0200296 }
297
298 parsedHeader[headerName] = parsedHeaderData
299 }
300
301 return mail.Header(parsedHeader), nil
302}
303
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200304func isEmbeddedFile(part *multipart.Part) bool {
305 return part.Header.Get("Content-Transfer-Encoding") != ""
306}
307
308func decodeEmbeddedFile(part *multipart.Part) (ef EmbeddedFile, err error) {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200309 cid := decodeMimeSentence(part.Header.Get("Content-Id"))
Dusan Kasan428369f2020-02-24 00:47:31 +0100310 decoded, err := decodeContent(part, part.Header.Get("Content-Transfer-Encoding"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200311 if err != nil {
312 return
313 }
314
315 ef.CID = strings.Trim(cid, "<>")
316 ef.Data = decoded
317 ef.ContentType = part.Header.Get("Content-Type")
318
319 return
320}
321
322func isAttachment(part *multipart.Part) bool {
323 return part.FileName() != ""
324}
325
326func decodeAttachment(part *multipart.Part) (at Attachment, err error) {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200327 filename := decodeMimeSentence(part.FileName())
Dusan Kasan428369f2020-02-24 00:47:31 +0100328 decoded, err := decodeContent(part, part.Header.Get("Content-Transfer-Encoding"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200329 if err != nil {
330 return
331 }
332
333 at.Filename = filename
334 at.Data = decoded
335 at.ContentType = strings.Split(part.Header.Get("Content-Type"), ";")[0]
336
337 return
338}
339
Dusan Kasan428369f2020-02-24 00:47:31 +0100340func decodeContent(content io.Reader, encoding string) (io.Reader, error) {
341 switch encoding {
342 case "base64":
343 decoded := base64.NewDecoder(base64.StdEncoding, content)
344 b, err := ioutil.ReadAll(decoded)
345 if err != nil {
346 return nil, err
347 }
348
349 return bytes.NewReader(b), nil
Dusan Kasan3325e732020-04-04 11:46:04 +0200350 case "7bit":
351 dd, err := ioutil.ReadAll(content)
352 if err != nil {
353 return nil, err
354 }
355
356 return bytes.NewReader(dd), nil
Dusan Kasan428369f2020-02-24 00:47:31 +0100357 case "":
358 return content, nil
359 default:
360 return nil, fmt.Errorf("unknown encoding: %s", encoding)
361 }
362}
363
Dusan Kasane668cf22017-04-18 12:56:51 +0200364type headerParser struct {
365 header *mail.Header
Dusan Kasanb974c632017-04-18 12:58:42 +0200366 err error
Dusan Kasane668cf22017-04-18 12:56:51 +0200367}
368
369func (hp headerParser) parseAddress(s string) (ma *mail.Address) {
370 if hp.err != nil {
371 return nil
372 }
373
374 if strings.Trim(s, " \n") != "" {
375 ma, hp.err = mail.ParseAddress(s)
376
377 return ma
378 }
379
380 return nil
381}
382
383func (hp headerParser) parseAddressList(s string) (ma []*mail.Address) {
384 if hp.err != nil {
385 return
386 }
387
388 if strings.Trim(s, " \n") != "" {
389 ma, hp.err = mail.ParseAddressList(s)
390 return
391 }
392
393 return
394}
395
396func (hp headerParser) parseTime(s string) (t time.Time) {
Dusan Kasanb974c632017-04-18 12:58:42 +0200397 if hp.err != nil || s == "" {
Dusan Kasane668cf22017-04-18 12:56:51 +0200398 return
399 }
400
Dusan Kasan88226cf2020-04-04 11:13:06 +0200401 formats := []string{
402 time.RFC1123Z,
403 "Mon, 2 Jan 2006 15:04:05 -0700",
404 time.RFC1123Z + " (MST)",
405 "Mon, 2 Jan 2006 15:04:05 -0700 (MST)",
Dusan Kasane668cf22017-04-18 12:56:51 +0200406 }
407
Dusan Kasan88226cf2020-04-04 11:13:06 +0200408 for _, format := range formats {
409 t, hp.err = time.Parse(format, s)
410 if hp.err == nil {
411 return
412 }
413 }
Dusan Kasane668cf22017-04-18 12:56:51 +0200414
415 return
416}
417
418func (hp headerParser) parseMessageId(s string) string {
419 if hp.err != nil {
420 return ""
421 }
422
423 return strings.Trim(s, "<> ")
424}
425
426func (hp headerParser) parseMessageIdList(s string) (result []string) {
427 if hp.err != nil {
428 return
429 }
430
431 for _, p := range strings.Split(s, " ") {
432 if strings.Trim(p, " \n") != "" {
433 result = append(result, hp.parseMessageId(p))
434 }
435 }
436
437 return
438}
439
Dusan Kasan1a966482017-04-18 10:45:25 +0200440// Attachment with filename, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200441type Attachment struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200442 Filename string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200443 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200444 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200445}
446
Dusan Kasan1a966482017-04-18 10:45:25 +0200447// EmbeddedFile with content id, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200448type EmbeddedFile struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200449 CID string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200450 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200451 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200452}
453
Dusan Kasan1a966482017-04-18 10:45:25 +0200454// Email with fields for all the headers defined in RFC5322 with it's attachments and
Dusan Kasan17e497e2017-04-10 22:44:22 +0200455type Email struct {
456 Header mail.Header
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200457
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200458 Subject string
459 Sender *mail.Address
460 From []*mail.Address
461 ReplyTo []*mail.Address
462 To []*mail.Address
463 Cc []*mail.Address
464 Bcc []*mail.Address
465 Date time.Time
466 MessageID string
467 InReplyTo []string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200468 References []string
469
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200470 ResentFrom []*mail.Address
471 ResentSender *mail.Address
472 ResentTo []*mail.Address
473 ResentDate time.Time
474 ResentCc []*mail.Address
475 ResentBcc []*mail.Address
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200476 ResentMessageID string
477
Dusan Kasan428369f2020-02-24 00:47:31 +0100478 ContentType string
479 Content io.Reader
480
Dusan Kasan17e497e2017-04-10 22:44:22 +0200481 HTMLBody string
482 TextBody string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200483
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200484 Attachments []Attachment
Dusan Kasan17e497e2017-04-10 22:44:22 +0200485 EmbeddedFiles []EmbeddedFile
Dusan Kasan428369f2020-02-24 00:47:31 +0100486}