-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
112 lines (98 loc) · 2.13 KB
/
parse.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package mailprint
import (
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/mail"
"strings"
"time"
)
type Email struct {
Subject string
From []*mail.Address
To []*mail.Address
Cc []*mail.Address
Date time.Time
TextBody string
}
func Parse(r io.Reader) (*Email, error) {
msg, err := mail.ReadMessage(r)
if err != nil {
return nil, fmt.Errorf("mail.ReadMessage: %w", err)
}
h := msg.Header
e := Email{}
var wd mime.WordDecoder
e.Subject, err = wd.DecodeHeader(h.Get("Subject"))
if err != nil {
return nil, err
}
e.Date, err = h.Date()
if err != nil {
return nil, err
}
e.To, err = h.AddressList("To")
if err != nil {
return nil, fmt.Errorf("header 'To': %w", err)
}
e.From, err = h.AddressList("From")
if err != nil {
return nil, fmt.Errorf("header 'From': %w", err)
}
e.Cc, err = h.AddressList("Cc")
if err != nil && err != mail.ErrHeaderNotPresent {
return nil, fmt.Errorf("header 'Cc': %w", err)
}
e.TextBody, err = parseTextBody(msg.Header.Get("Content-Type"), msg.Body)
if err != nil {
return nil, err
}
return &e, nil
}
func parseTextBody(ctHdr string, r io.Reader) (string, error) {
var (
contentType string
params map[string]string
err error
)
if ctHdr == "" {
contentType = "text/plain"
} else {
contentType, params, err = mime.ParseMediaType(ctHdr)
if err != nil {
return "", err
}
}
switch contentType {
case "text/plain":
b, err := io.ReadAll(r)
if err != nil {
return "", err
}
return strings.TrimSuffix(string(b), "\n"), nil
case "text/html":
return "", fmt.Errorf("unsupported content type %q", contentType)
case "multipart/alternative":
fallthrough
case "multipart/related":
fallthrough
case "multipart/report":
fallthrough
case "multipart/mixed":
mpr := multipart.NewReader(r, params["boundary"])
for {
part, err := mpr.NextPart()
if err == io.EOF {
break
} else if err != nil {
return "", err
}
return parseTextBody(part.Header.Get("Content-Type"), part)
}
return "", errors.New("missing plain text content")
default:
return "", fmt.Errorf("unknown content type %q", contentType)
}
}