blob: 2bbb12338bc109ca866236ab9e3b391b13c10da3 [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) {
Dusan Kasane668cf22017-04-18 12:56:51 +020058 hp := headerParser{header: &header}
59
Dusan Kasanb49ceb62017-04-13 00:00:36 +020060 email.Subject = header.Get("Subject")
Dusan Kasane668cf22017-04-18 12:56:51 +020061 email.From = hp.parseAddressList(header.Get("From"))
62 email.Sender = hp.parseAddress(header.Get("Sender"))
63 email.ReplyTo = hp.parseAddressList(header.Get("Reply-To"))
64 email.To = hp.parseAddressList(header.Get("To"))
65 email.Cc = hp.parseAddressList(header.Get("Cc"))
66 email.Bcc = hp.parseAddressList(header.Get("Bcc"))
67 email.Date = hp.parseTime(header.Get("Date"))
68 email.ResentFrom = hp.parseAddressList(header.Get("Resent-From"))
69 email.ResentSender = hp.parseAddress(header.Get("Resent-Sender"))
70 email.ResentTo = hp.parseAddressList(header.Get("Resent-To"))
71 email.ResentCc = hp.parseAddressList(header.Get("Resent-Cc"))
72 email.ResentBcc = hp.parseAddressList(header.Get("Resent-Bcc"))
73 email.ResentMessageID = hp.parseMessageId(header.Get("Resent-Message-ID"))
74 email.MessageID = hp.parseMessageId(header.Get("Message-ID"))
75 email.InReplyTo = hp.parseMessageIdList(header.Get("In-Reply-To"))
76 email.References = hp.parseMessageIdList(header.Get("References"))
77 email.ResentDate = hp.parseTime(header.Get("Resent-Date"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +020078
Dusan Kasane668cf22017-04-18 12:56:51 +020079 if hp.err != nil {
80 err = hp.err
Dusan Kasanb49ceb62017-04-13 00:00:36 +020081 return
82 }
83
Dusan Kasanb49ceb62017-04-13 00:00:36 +020084 //decode whole header for easier access to extra fields
85 //todo: should we decode? aren't only standard fields mime encoded?
86 email.Header, err = decodeHeaderMime(header)
87 if err != nil {
88 return
89 }
90
91 return
92}
93
94func parseContentType(contentTypeHeader string) (contentType string, params map[string]string, err error) {
95 if contentTypeHeader == "" {
Dusan Kasan45ca2642017-04-18 10:39:35 +020096 contentType = contentTypeTextPlain
Dusan Kasanb49ceb62017-04-13 00:00:36 +020097 return
98 }
99
100 return mime.ParseMediaType(contentTypeHeader)
101}
102
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200103func parseMultipartAlternative(msg io.Reader, boundary string) (textBody, htmlBody string, embeddedFiles []EmbeddedFile, err error) {
104 pmr := multipart.NewReader(msg, boundary)
105 for {
106 part, err := pmr.NextPart()
107
108 if err == io.EOF {
109 break
110 } else if err != nil {
111 return textBody, htmlBody, embeddedFiles, err
112 }
113
114 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
Dusan Kasanc661cc02017-04-18 10:51:51 +0200115 if err != nil {
116 return textBody, htmlBody, embeddedFiles, err
117 }
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200118
119 switch contentType {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200120 case contentTypeTextPlain:
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200121 ppContent, err := ioutil.ReadAll(part)
122 if err != nil {
123 return textBody, htmlBody, embeddedFiles, err
124 }
125
126 textBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +0200127 case contentTypeTextHtml:
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200128 ppContent, err := ioutil.ReadAll(part)
129 if err != nil {
130 return textBody, htmlBody, embeddedFiles, err
131 }
132
133 htmlBody += strings.TrimSuffix(string(ppContent[:]), "\n")
Dusan Kasan45ca2642017-04-18 10:39:35 +0200134 case contentTypeMultipartRelated:
Dusan Kasan1a966482017-04-18 10:45:25 +0200135 tb, hb, ef, err := parseMultipartAlternative(part, params["boundary"])
136 if err != nil {
137 return textBody, htmlBody, embeddedFiles, err
138 }
139
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200140 htmlBody += hb
141 textBody += tb
142 embeddedFiles = append(embeddedFiles, ef...)
143 default:
144 if isEmbeddedFile(part) {
145 ef, err := decodeEmbeddedFile(part)
146 if err != nil {
147 return textBody, htmlBody, embeddedFiles, err
148 }
149
150 embeddedFiles = append(embeddedFiles, ef)
151 } else {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200152 return textBody, htmlBody, embeddedFiles, fmt.Errorf("Can't process multipart/alternative inner mime type: %s", contentType)
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200153 }
154 }
155 }
156
157 return textBody, htmlBody, embeddedFiles, err
158}
159
160func parseMultipartMixed(msg io.Reader, boundary string) (textBody, htmlBody string, attachments []Attachment, embeddedFiles []EmbeddedFile, err error) {
161 mr := multipart.NewReader(msg, boundary)
162 for {
163 part, err := mr.NextPart()
164 if err == io.EOF {
165 break
166 } else if err != nil {
167 return textBody, htmlBody, attachments, embeddedFiles, err
168 }
169
170 contentType, params, err := mime.ParseMediaType(part.Header.Get("Content-Type"))
171 if err != nil {
172 return textBody, htmlBody, attachments, embeddedFiles, err
173 }
174
Dusan Kasan45ca2642017-04-18 10:39:35 +0200175 if contentType == contentTypeMultipartAlternative {
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200176 textBody, htmlBody, embeddedFiles, err = parseMultipartAlternative(part, params["boundary"])
177 if err != nil {
178 return textBody, htmlBody, attachments, embeddedFiles, err
179 }
180 } else if isAttachment(part) {
181 at, err := decodeAttachment(part)
182 if err != nil {
183 return textBody, htmlBody, attachments, embeddedFiles, err
184 }
185
186 attachments = append(attachments, at)
187 } else {
Dusan Kasan45ca2642017-04-18 10:39:35 +0200188 return textBody, htmlBody, attachments, embeddedFiles, fmt.Errorf("Unknown multipart/mixed nested mime type: %s", contentType)
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200189 }
190 }
191
192 return textBody, htmlBody, attachments, embeddedFiles, err
Dusan Kasan17e497e2017-04-10 22:44:22 +0200193}
194
195func decodeMimeSentence(s string) (string, error) {
196 result := []string{}
197 ss := strings.Split(s, " ")
198
199 for _, word := range ss {
200 dec := new(mime.WordDecoder)
201 w, err := dec.Decode(word)
202 if err != nil {
203 if len(result) == 0 {
204 w = word
205 } else {
206 w = " " + word
207 }
208 }
209
210 result = append(result, w)
211 }
212
213 return strings.Join(result, ""), nil
214}
215
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200216func decodeHeaderMime(header mail.Header) (mail.Header, error) {
Dusan Kasan17e497e2017-04-10 22:44:22 +0200217 parsedHeader := map[string][]string{}
218
219 for headerName, headerData := range header {
220
221 parsedHeaderData := []string{}
222 for _, headerValue := range headerData {
223 decodedHeaderValue, err := decodeMimeSentence(headerValue)
224 if err != nil {
225 return mail.Header{}, err
226 }
227 parsedHeaderData = append(parsedHeaderData, decodedHeaderValue)
228 }
229
230 parsedHeader[headerName] = parsedHeaderData
231 }
232
233 return mail.Header(parsedHeader), nil
234}
235
236func decodePartData(part *multipart.Part) (io.Reader, error) {
237 encoding := part.Header.Get("Content-Transfer-Encoding")
238
239 if encoding == "base64" {
240 dr := base64.NewDecoder(base64.StdEncoding, part)
241 dd, err := ioutil.ReadAll(dr)
242 if err != nil {
243 return nil, err
244 }
245
246 return bytes.NewReader(dd), nil
Dusan Kasan17e497e2017-04-10 22:44:22 +0200247 }
Dusan Kasan45ca2642017-04-18 10:39:35 +0200248
249 return nil, fmt.Errorf("Unknown encoding: %s", encoding)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200250}
251
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200252func isEmbeddedFile(part *multipart.Part) bool {
253 return part.Header.Get("Content-Transfer-Encoding") != ""
254}
255
256func decodeEmbeddedFile(part *multipart.Part) (ef EmbeddedFile, err error) {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200257 cid, err := decodeMimeSentence(part.Header.Get("Content-Id"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200258 if err != nil {
259 return
260 }
261
262 decoded, err := decodePartData(part)
263 if err != nil {
264 return
265 }
266
267 ef.CID = strings.Trim(cid, "<>")
268 ef.Data = decoded
269 ef.ContentType = part.Header.Get("Content-Type")
270
271 return
272}
273
274func isAttachment(part *multipart.Part) bool {
275 return part.FileName() != ""
276}
277
278func decodeAttachment(part *multipart.Part) (at Attachment, err error) {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200279 filename, err := decodeMimeSentence(part.FileName())
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200280 if err != nil {
281 return
282 }
283
284 decoded, err := decodePartData(part)
285 if err != nil {
286 return
287 }
288
289 at.Filename = filename
290 at.Data = decoded
291 at.ContentType = strings.Split(part.Header.Get("Content-Type"), ";")[0]
292
293 return
294}
295
Dusan Kasane668cf22017-04-18 12:56:51 +0200296type headerParser struct {
297 header *mail.Header
298 err error
299}
300
301func (hp headerParser) parseAddress(s string) (ma *mail.Address) {
302 if hp.err != nil {
303 return nil
304 }
305
306 if strings.Trim(s, " \n") != "" {
307 ma, hp.err = mail.ParseAddress(s)
308
309 return ma
310 }
311
312 return nil
313}
314
315func (hp headerParser) parseAddressList(s string) (ma []*mail.Address) {
316 if hp.err != nil {
317 return
318 }
319
320 if strings.Trim(s, " \n") != "" {
321 ma, hp.err = mail.ParseAddressList(s)
322 return
323 }
324
325 return
326}
327
328func (hp headerParser) parseTime(s string) (t time.Time) {
329 if hp.err != nil || s == ""{
330 return
331 }
332
333 t, hp.err = time.Parse(time.RFC1123Z, s)
334 if hp.err == nil {
335 return t
336 }
337
338 t, hp.err = time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", s)
339
340 return
341}
342
343func (hp headerParser) parseMessageId(s string) string {
344 if hp.err != nil {
345 return ""
346 }
347
348 return strings.Trim(s, "<> ")
349}
350
351func (hp headerParser) parseMessageIdList(s string) (result []string) {
352 if hp.err != nil {
353 return
354 }
355
356 for _, p := range strings.Split(s, " ") {
357 if strings.Trim(p, " \n") != "" {
358 result = append(result, hp.parseMessageId(p))
359 }
360 }
361
362 return
363}
364
Dusan Kasan1a966482017-04-18 10:45:25 +0200365// Attachment with filename, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200366type Attachment struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200367 Filename string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200368 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200369 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200370}
371
Dusan Kasan1a966482017-04-18 10:45:25 +0200372// EmbeddedFile with content id, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200373type EmbeddedFile struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200374 CID string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200375 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200376 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200377}
378
Dusan Kasan1a966482017-04-18 10:45:25 +0200379// Email with fields for all the headers defined in RFC5322 with it's attachments and
Dusan Kasan17e497e2017-04-10 22:44:22 +0200380type Email struct {
381 Header mail.Header
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200382
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200383 Subject string
384 Sender *mail.Address
385 From []*mail.Address
386 ReplyTo []*mail.Address
387 To []*mail.Address
388 Cc []*mail.Address
389 Bcc []*mail.Address
390 Date time.Time
391 MessageID string
392 InReplyTo []string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200393 References []string
394
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200395 ResentFrom []*mail.Address
396 ResentSender *mail.Address
397 ResentTo []*mail.Address
398 ResentDate time.Time
399 ResentCc []*mail.Address
400 ResentBcc []*mail.Address
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200401 ResentMessageID string
402
Dusan Kasan17e497e2017-04-10 22:44:22 +0200403 HTMLBody string
404 TextBody string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200405
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200406 Attachments []Attachment
Dusan Kasan17e497e2017-04-10 22:44:22 +0200407 EmbeddedFiles []EmbeddedFile
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200408}