blob: 6ee06243ee1713df567dcc284451c811f35e28a6 [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 Kasanf4376a62017-05-23 21:03:55 +020060 email.Subject = decodeMimeSentence(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
Dusan Kasanf4376a62017-05-23 21:03:55 +0200195func decodeMimeSentence(s string) string {
Dusan Kasan17e497e2017-04-10 22:44:22 +0200196 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
Dusan Kasanf4376a62017-05-23 21:03:55 +0200213 return strings.Join(result, "")
Dusan Kasan17e497e2017-04-10 22:44:22 +0200214}
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 {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200223 parsedHeaderData = append(parsedHeaderData, decodeMimeSentence(headerValue))
Dusan Kasan17e497e2017-04-10 22:44:22 +0200224 }
225
226 parsedHeader[headerName] = parsedHeaderData
227 }
228
229 return mail.Header(parsedHeader), nil
230}
231
232func decodePartData(part *multipart.Part) (io.Reader, error) {
233 encoding := part.Header.Get("Content-Transfer-Encoding")
234
235 if encoding == "base64" {
236 dr := base64.NewDecoder(base64.StdEncoding, part)
237 dd, err := ioutil.ReadAll(dr)
238 if err != nil {
239 return nil, err
240 }
241
242 return bytes.NewReader(dd), nil
Dusan Kasan17e497e2017-04-10 22:44:22 +0200243 }
Dusan Kasan45ca2642017-04-18 10:39:35 +0200244
245 return nil, fmt.Errorf("Unknown encoding: %s", encoding)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200246}
247
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200248func isEmbeddedFile(part *multipart.Part) bool {
249 return part.Header.Get("Content-Transfer-Encoding") != ""
250}
251
252func decodeEmbeddedFile(part *multipart.Part) (ef EmbeddedFile, err error) {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200253 cid := decodeMimeSentence(part.Header.Get("Content-Id"))
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200254 decoded, err := decodePartData(part)
255 if err != nil {
256 return
257 }
258
259 ef.CID = strings.Trim(cid, "<>")
260 ef.Data = decoded
261 ef.ContentType = part.Header.Get("Content-Type")
262
263 return
264}
265
266func isAttachment(part *multipart.Part) bool {
267 return part.FileName() != ""
268}
269
270func decodeAttachment(part *multipart.Part) (at Attachment, err error) {
Dusan Kasanf4376a62017-05-23 21:03:55 +0200271 filename := decodeMimeSentence(part.FileName())
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200272 decoded, err := decodePartData(part)
273 if err != nil {
274 return
275 }
276
277 at.Filename = filename
278 at.Data = decoded
279 at.ContentType = strings.Split(part.Header.Get("Content-Type"), ";")[0]
280
281 return
282}
283
Dusan Kasane668cf22017-04-18 12:56:51 +0200284type headerParser struct {
285 header *mail.Header
Dusan Kasanb974c632017-04-18 12:58:42 +0200286 err error
Dusan Kasane668cf22017-04-18 12:56:51 +0200287}
288
289func (hp headerParser) parseAddress(s string) (ma *mail.Address) {
290 if hp.err != nil {
291 return nil
292 }
293
294 if strings.Trim(s, " \n") != "" {
295 ma, hp.err = mail.ParseAddress(s)
296
297 return ma
298 }
299
300 return nil
301}
302
303func (hp headerParser) parseAddressList(s string) (ma []*mail.Address) {
304 if hp.err != nil {
305 return
306 }
307
308 if strings.Trim(s, " \n") != "" {
309 ma, hp.err = mail.ParseAddressList(s)
310 return
311 }
312
313 return
314}
315
316func (hp headerParser) parseTime(s string) (t time.Time) {
Dusan Kasanb974c632017-04-18 12:58:42 +0200317 if hp.err != nil || s == "" {
Dusan Kasane668cf22017-04-18 12:56:51 +0200318 return
319 }
320
321 t, hp.err = time.Parse(time.RFC1123Z, s)
322 if hp.err == nil {
323 return t
324 }
325
326 t, hp.err = time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", s)
327
328 return
329}
330
331func (hp headerParser) parseMessageId(s string) string {
332 if hp.err != nil {
333 return ""
334 }
335
336 return strings.Trim(s, "<> ")
337}
338
339func (hp headerParser) parseMessageIdList(s string) (result []string) {
340 if hp.err != nil {
341 return
342 }
343
344 for _, p := range strings.Split(s, " ") {
345 if strings.Trim(p, " \n") != "" {
346 result = append(result, hp.parseMessageId(p))
347 }
348 }
349
350 return
351}
352
Dusan Kasan1a966482017-04-18 10:45:25 +0200353// Attachment with filename, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200354type Attachment struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200355 Filename string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200356 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200357 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200358}
359
Dusan Kasan1a966482017-04-18 10:45:25 +0200360// EmbeddedFile with content id, content type and data (as a io.Reader)
Dusan Kasan17e497e2017-04-10 22:44:22 +0200361type EmbeddedFile struct {
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200362 CID string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200363 ContentType string
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200364 Data io.Reader
Dusan Kasan17e497e2017-04-10 22:44:22 +0200365}
366
Dusan Kasan1a966482017-04-18 10:45:25 +0200367// Email with fields for all the headers defined in RFC5322 with it's attachments and
Dusan Kasan17e497e2017-04-10 22:44:22 +0200368type Email struct {
369 Header mail.Header
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200370
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200371 Subject string
372 Sender *mail.Address
373 From []*mail.Address
374 ReplyTo []*mail.Address
375 To []*mail.Address
376 Cc []*mail.Address
377 Bcc []*mail.Address
378 Date time.Time
379 MessageID string
380 InReplyTo []string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200381 References []string
382
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200383 ResentFrom []*mail.Address
384 ResentSender *mail.Address
385 ResentTo []*mail.Address
386 ResentDate time.Time
387 ResentCc []*mail.Address
388 ResentBcc []*mail.Address
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200389 ResentMessageID string
390
Dusan Kasan17e497e2017-04-10 22:44:22 +0200391 HTMLBody string
392 TextBody string
Dusan Kasanb49ceb62017-04-13 00:00:36 +0200393
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200394 Attachments []Attachment
Dusan Kasan17e497e2017-04-10 22:44:22 +0200395 EmbeddedFiles []EmbeddedFile
Dusan Kasan4595dfe2017-04-13 00:38:24 +0200396}