forked from mnako/letters
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathletters.go
83 lines (70 loc) · 2.53 KB
/
letters.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package letters
import (
"fmt"
"io"
"net/mail"
"strings"
"golang.org/x/net/html/charset"
)
func ParseEmail(r io.Reader) (Email, error) {
var email Email
msg, err := mail.ReadMessage(r)
if err != nil {
return email, fmt.Errorf("letters.ParseEmail: cannot read message: %w", err)
}
headers, err := ParseHeaders(msg.Header)
if err != nil {
return email, fmt.Errorf("letters.ParseEmail: cannot parse headers: %w", err)
}
email = Email{
Headers: headers,
}
encoding, _ := charset.Lookup(email.Headers.ContentType.Params["charset"])
cte, err := parseContentTransferEncoding(msg.Header.Get("Content-Transfer-Encoding"))
if err != nil {
return email, fmt.Errorf("letters.ParseEmail: cannot parse Content-Transfer-Encoding: %w", err)
}
if email.Headers.ContentType.ContentType == contentTypeTextPlain {
email.Text, err = parseText(msg.Body, encoding, cte)
if err != nil {
return email, fmt.Errorf("letters.ParseEmail: cannot parse plain text: %w", err)
}
} else if email.Headers.ContentType.ContentType == contentTypeTextEnriched {
email.EnrichedText, err = parseText(msg.Body, encoding, cte)
if err != nil {
return email, fmt.Errorf("letters.ParseEmail: cannot parse enriched text: %w", err)
}
} else if email.Headers.ContentType.ContentType == contentTypeTextHtml {
email.HTML, err = parseText(msg.Body, encoding, cte)
if err != nil {
return email, fmt.Errorf("letters.ParseEmail: cannot parse html text: %w", err)
}
} else if strings.HasPrefix(email.Headers.ContentType.ContentType, contentTypeMultipartPrefix) {
boundary := email.Headers.ContentType.Params["boundary"]
emailBodies, err := parsePart(msg.Body, email.Headers.ContentType, boundary)
if err != nil {
return email, fmt.Errorf(
"letters.ParseEmail: cannot parse part %q with boundary %q: %w",
email.Headers.ContentType.ContentType,
boundary,
err)
}
email.Text = emailBodies.text
email.EnrichedText = emailBodies.enrichedText
email.HTML = emailBodies.html
email.InlineFiles = emailBodies.InlineFiles
email.AttachedFiles = emailBodies.AttachedFiles
} else {
afl, err := decodeAttachmentFileFromBody(msg.Body, email.Headers, cte)
if err != nil {
return email, fmt.Errorf(
"letters.decoders.ParseEmail: cannot decode attached file content from body: %w",
err)
}
email.AttachedFiles = append(email.AttachedFiles, afl)
}
email.Text = normalizeMultilineString(email.Text)
email.EnrichedText = normalizeMultilineString(email.EnrichedText)
email.HTML = normalizeMultilineString(email.HTML)
return email, nil
}