blob: 293433fa24fd9bd3aea668d417734f6c83edf3a1 [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 Kasanb49ceb62017-04-13 00:00:36 +020034 contentType, params, err := parseContentType(msg.Header.Get("Content-Type"))
Dusan Kasan17e497e2017-04-10 22:44:22 +020035 if err != nil {
Dusan Kasanb49ceb62017-04-13 00:00:36 +020036 return
Dusan Kasan17e497e2017-04-10 22:44:22 +020037 }
38
Dusan Kasanb49ceb62017-04-13 00:00:36 +020039 switch contentType {
Dusan Kasan45ca2642017-04-18 10:39:35 +020040 case contentTypeMultipartMixed:
Dusan Kasan17e497e2017-04-10 22:44:22 +020041 email.TextBody, email.HTMLBody, email.Attachments, email.EmbeddedFiles, err = parseMultipartMixed(msg.Body, params["boundary"])
Dusan Kasan45ca2642017-04-18 10:39:35 +020042 case contentTypeMultipartAlternative:
Dusan Kasan17e497e2017-04-10 22:44:22 +020043 email.TextBody, email.HTMLBody, email.EmbeddedFiles, err = parseMultipartAlternative(msg.Body, params["boundary"])
Dusan Kasan45ca2642017-04-18 10:39:35 +020044 case contentTypeTextPlain:
Dusan Kasan17e497e2017-04-10 22:44:22 +020045 message, _ := ioutil.ReadAll(msg.Body)
46 email.TextBody = strings.TrimSuffix(string(message[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +020047 case contentTypeTextHtml:
Dusan Kasan17e497e2017-04-10 22:44:22 +020048 message, _ := ioutil.ReadAll(msg.Body)
49 email.HTMLBody = strings.TrimSuffix(string(message[:]), "\n")
Dusan Kasanb49ceb62017-04-13 00:00:36 +020050 default:
Dusan Kasan45ca2642017-04-18 10:39:35 +020051 err = fmt.Errorf("Unknown top level mime type: %s", contentType)
Dusan Kasan17e497e2017-04-10 22:44:22 +020052 }
53
Dusan Kasanb49ceb62017-04-13 00:00:36 +020054 return
55}
56
57func createEmailFromHeader(header mail.Header) (email Email, err error) {
58 email.Subject = header.Get("Subject")
59
60 email.From, err = parseAddressList(header.Get("From"))
61 if err != nil {
62 return
63 }
64
65 email.Sender, err = parseAddress(header.Get("Sender"))
66 if err != nil {
67 return
68 }
69
70 email.ReplyTo, err = parseAddressList(header.Get("Reply-To"))
71 if err != nil {
72 return
73 }
74
75 email.To, err = parseAddressList(header.Get("To"))
76 if err != nil {
77 return
78 }
79
80 email.Cc, err = parseAddressList(header.Get("Cc"))
81 if err != nil {
82 return
83 }
84
85 email.Bcc, err = parseAddressList(header.Get("Bcc"))
86 if err != nil {
87 return
88 }
89
90 email.Date, err = parseTime(header.Get("Date"))
91 if err != nil {
92 return
93 }
94
95 email.ResentFrom, err = parseAddressList(header.Get("Resent-From"))
96 if err != nil {
97 return
98 }
99
100 email.ResentSender, err = parseAddress(header.Get("Resent-Sender"))
101 if err != nil {
102 return
103 }
104
105 email.ResentTo, err = parseAddressList(header.Get("Resent-To"))
106 if err != nil {
107 return
108 }
109
110 email.ResentCc, err = parseAddressList(header.Get("Resent-Cc"))
111 if err != nil {
112 return
113 }
114
115 email.ResentBcc, err = parseAddressList(header.Get("Resent-Bcc"))
116 if err != nil {
117 return
118 }
119
120 if header.Get("Resent-Date") == "" {
121 email.ResentDate = time.Time{}
122 } else {
123 email.ResentDate, err = parseTime(header.Get("Resent-Date"))
124 if err != nil {
125 return
126 }
127 }
128
129 email.ResentMessageID = parseMessageId(header.Get("Resent-Message-ID"))
130 email.MessageID = parseMessageId(header.Get("Message-ID"))
131 email.InReplyTo = parseMessageIdList(header.Get("In-Reply-To"))
132 email.References = parseMessageIdList(header.Get("References"))
133
134 //decode whole header for easier access to extra fields
135 //todo: should we decode? aren't only standard fields mime encoded?
136 email.Header, err = decodeHeaderMime(header)
137 if err != nil {
138 return
139 }
140
141 return
142}
143
144func parseContentType(contentTypeHeader string) (contentType string, params map[string]string, err error) {
145 if contentTypeHeader == "" {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200146 contentType = contentTypeTextPlain
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200147 return
148 }
149
150 return mime.ParseMediaType(contentTypeHeader)
151}
152
153func parseAddress(s string) (*mail.Address, error) {
154 if strings.Trim(s, " \n") != "" {
155 return mail.ParseAddress(s)
156 }
157
158 return nil, nil
159}
160
161func parseAddressList(s string) ([]*mail.Address, error) {
162 if strings.Trim(s, " \n") != "" {
163 return mail.ParseAddressList(s)
164 }
165
166 return []*mail.Address{}, nil
167}
168
169func parseTime(s string) (time.Time, error) {
170 t, err := time.Parse(time.RFC1123Z, s)
171 if err == nil {
172 return t, err
173 }
174
175 return time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", s)
176}
177
178func parseMessageId(s string) string {
179 return strings.Trim(s, "<> ")
180}
181
182func parseMessageIdList(s string) (result []string) {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200183 for _, p := range strings.Split(s, " ") {
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200184 if strings.Trim(p, " \n") != "" {
185 result = append(result, parseMessageId(p))
186 }
187 }
188
189 return
190}
191
192func parseMultipartAlternative(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
193 pmr := multipart.NewReader(msg, boundary)
194 for {
195 part, err := pmr.NextPart()
196
197 if err == io.EOF {
198 break
199 } else if err != nil {
200 return textBody, htmlBody, embeddedFiles, err
201 }
202
203 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
204
205 switch contentType {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200206 case contentTypeTextPlain:
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200207 ppContent, err := ioutil.ReadAll(part)
208 if err != nil {
209 return textBody, htmlBody, embeddedFiles, err
210 }
211
212 textBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +0200213 case contentTypeTextHtml:
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200214 ppContent, err := ioutil.ReadAll(part)
215 if err != nil {
216 return textBody, htmlBody, embeddedFiles, err
217 }
218
219 htmlBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +0200220 case contentTypeMultipartRelated:
221 tb, hb, ef, er := parseMultipartAlternative(part, params["boundary"])
222 err = er
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200223 htmlBody += hb
224 textBody += tb
225 embeddedFiles = append(embeddedFiles, ef...)
226 default:
227 if isEmbeddedFile(part) {
228 ef, err := decodeEmbeddedFile(part)
229 if err != nil {
230 return textBody, htmlBody, embeddedFiles, err
231 }
232
233 embeddedFiles = append(embeddedFiles, ef)
234 } else {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200235 return textBody, htmlBody, embeddedFiles, fmt.Errorf("Can't process multipart/alternative inner mime type: %s", contentType)
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200236 }
237 }
238 }
239
240 return textBody, htmlBody, embeddedFiles, err
241}
242
243func parseMultipartMixed(msg io.Reader, boundary string) (textBody, htmlBody string, attachments []Attachment, embeddedFiles []EmbeddedFile, err error) {
244 mr := multipart.NewReader(msg, boundary)
245 for {
246 part, err := mr.NextPart()
247 if err == io.EOF {
248 break
249 } else if err != nil {
250 return textBody, htmlBody, attachments, embeddedFiles, err
251 }
252
253 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
254 if err != nil {
255 return textBody, htmlBody, attachments, embeddedFiles, err
256 }
257
Dusan Kasan45ca2642017-04-18 10:39:35 +0200258 if contentType == contentTypeMultipartAlternative {
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200259 textBody, htmlBody, embeddedFiles, err = parseMultipartAlternative(part, params["boundary"])
260 if err != nil {
261 return textBody, htmlBody, attachments, embeddedFiles, err
262 }
263 } else if isAttachment(part) {
264 at, err := decodeAttachment(part)
265 if err != nil {
266 return textBody, htmlBody, attachments, embeddedFiles, err
267 }
268
269 attachments = append(attachments, at)
270 } else {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200271 return textBody, htmlBody, attachments, embeddedFiles, fmt.Errorf("Unknown multipart/mixed nested mime type: %s", contentType)
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200272 }
273 }
274
275 return textBody, htmlBody, attachments, embeddedFiles, err
Dusan Kasan17e497e2017-04-10 22:44:22 +0200276}
277
278func decodeMimeSentence(s string) (string, error) {
279 result := []string{}
280 ss := strings.Split(s, " ")
281
282 for _, word := range ss {
283 dec := new(mime.WordDecoder)
284 w, err := dec.Decode(word)
285 if err != nil {
286 if len(result) == 0 {
287 w = word
288 } else {
289 w = " " + word
290 }
291 }
292
293 result = append(result, w)
294 }
295
296 return strings.Join(result, ""), nil
297}
298
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200299func decodeHeaderMime(header mail.Header) (mail.Header, error) {
Dusan Kasan17e497e2017-04-10 22:44:22 +0200300 parsedHeader := map[string][]string{}
301
302 for headerName, headerData := range header {
303
304 parsedHeaderData := []string{}
305 for _, headerValue := range headerData {
306 decodedHeaderValue, err := decodeMimeSentence(headerValue)
307 if err != nil {
308 return mail.Header{}, err
309 }
310 parsedHeaderData = append(parsedHeaderData, decodedHeaderValue)
311 }
312
313 parsedHeader[headerName] = parsedHeaderData
314 }
315
316 return mail.Header(parsedHeader), nil
317}
318
319func decodePartData(part *multipart.Part) (io.Reader, error) {
320 encoding := part.Header.Get("Content-Transfer-Encoding")
321
322 if encoding == "base64" {
323 dr := base64.NewDecoder(base64.StdEncoding, part)
324 dd, err := ioutil.ReadAll(dr)
325 if err != nil {
326 return nil, err
327 }
328
329 return bytes.NewReader(dd), nil
Dusan Kasan17e497e2017-04-10 22:44:22 +0200330 }
Dusan Kasan45ca2642017-04-18 10:39:35 +0200331
332 return nil, fmt.Errorf("Unknown encoding: %s", encoding)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200333}
334
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200335func isEmbeddedFile(part *multipart.Part) bool {
336 return part.Header.Get("Content-Transfer-Encoding") != ""
337}
338
339func decodeEmbeddedFile(part *multipart.Part) (ef EmbeddedFile, err error) {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200340 cid, err := decodeMimeSentence(part.Header.Get("Content-Id"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200341 if err != nil {
342 return
343 }
344
345 decoded, err := decodePartData(part)
346 if err != nil {
347 return
348 }
349
350 ef.CID = strings.Trim(cid, "<>")
351 ef.Data = decoded
352 ef.ContentType = part.Header.Get("Content-Type")
353
354 return
355}
356
357func isAttachment(part *multipart.Part) bool {
358 return part.FileName() != ""
359}
360
361func decodeAttachment(part *multipart.Part) (at Attachment, err error) {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200362 filename, err := decodeMimeSentence(part.FileName())
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200363 if err != nil {
364 return
365 }
366
367 decoded, err := decodePartData(part)
368 if err != nil {
369 return
370 }
371
372 at.Filename = filename
373 at.Data = decoded
374 at.ContentType = strings.Split(part.Header.Get("Content-Type"), ";")[0]
375
376 return
377}
378
Dusan Kasan45ca2642017-04-18 10:39:35 +0200379// Represents email attachment with filename, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200380type Attachment struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200381 Filename string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200382 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200383 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200384}
385
Dusan Kasan45ca2642017-04-18 10:39:35 +0200386// Represents email embedded file with content id, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200387type EmbeddedFile struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200388 CID string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200389 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200390 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200391}
392
Dusan Kasan45ca2642017-04-18 10:39:35 +0200393// Represents email with fields for all the headers defined in RFC5322 with it's attachments and
Dusan Kasan17e497e2017-04-10 22:44:22 +0200394type Email struct {
395 Header mail.Header
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200396
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200397 Subject string
398 Sender *mail.Address
399 From []*mail.Address
400 ReplyTo []*mail.Address
401 To []*mail.Address
402 Cc []*mail.Address
403 Bcc []*mail.Address
404 Date time.Time
405 MessageID string
406 InReplyTo []string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200407 References []string
408
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200409 ResentFrom []*mail.Address
410 ResentSender *mail.Address
411 ResentTo []*mail.Address
412 ResentDate time.Time
413 ResentCc []*mail.Address
414 ResentBcc []*mail.Address
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200415 ResentMessageID string
416
Dusan Kasan17e497e2017-04-10 22:44:22 +0200417 HTMLBody string
418 TextBody string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200419
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200420 Attachments []Attachment
Dusan Kasan17e497e2017-04-10 22:44:22 +0200421 EmbeddedFiles []EmbeddedFile
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200422}