-
Notifications
You must be signed in to change notification settings - Fork 0
/
message_unpack.go
139 lines (113 loc) · 2.49 KB
/
message_unpack.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package mboxrd
import (
"encoding/base64"
"fmt"
"io"
"mime"
"mime/multipart"
"net/mail"
"os"
"strings"
"sync"
)
type getter interface {
Get(key string) string
}
func partsIterate(head getter, body io.Reader, emlbase string, errors chan error) {
mediaType, params, err := mime.ParseMediaType(head.Get("Content-Type"))
if err != nil || !strings.HasPrefix(mediaType, "multipart/") {
return
}
mr := multipart.NewReader(body, params["boundary"])
for {
p, err := mr.NextPart()
if err == io.EOF {
return
}
if err != nil {
errors <- MessageError(
fmt.Sprintf(
"Problem opening a part of the %q message: %s",
emlbase,
err.Error()))
return
}
partsIterate(p.Header, p, emlbase, errors)
unpackPart(p, emlbase, errors)
}
}
func unpackPart(part *multipart.Part, emlbase string, errors chan error) {
defer part.Close()
partFileName := part.FileName()
if partFileName == "" {
return
}
attachmentFileName := emlbase + " " + partFileName
attachmentFile, err := os.Create(attachmentFileName)
if err != nil {
errors <- MessageError(
fmt.Sprintf(
"Problem opening the %q file: %s",
attachmentFileName,
err.Error()))
return
}
defer attachmentFile.Close()
enc := part.Header.Get("Content-Transfer-Encoding")
var partReader io.Reader
switch enc {
case "", "7bit", "8bit":
partReader = part
case "base64", "BASE64", "Base64":
partReader = base64.NewDecoder(base64.StdEncoding, part)
default:
errors <- MessageError(
fmt.Sprintf(
"Attachment %q: unknown encoging %q",
attachmentFileName,
enc))
return
}
_, err = io.Copy(attachmentFile, partReader)
if err != nil {
errors <- MessageError(
fmt.Sprintf(
"Problem copying the %q part of the %q message: %s",
attachmentFile,
emlbase,
err.Error()))
return
}
}
func cutExt(fname string) string {
dotIdx := strings.LastIndex(fname, ".")
if dotIdx < 0 {
return fname
}
return fname[:dotIdx]
}
func UnpackMessage(eml string, errors chan error, wg *sync.WaitGroup) {
if wg != nil {
defer wg.Done()
}
f, err := os.Open(eml)
if err != nil {
errors <- MessageError(
fmt.Sprintf(
"Problem opening the %q message file for unpacking: %s",
eml,
err.Error()))
return
}
defer f.Close()
msg, err := mail.ReadMessage(f)
if err != nil {
errors <- MessageError(
fmt.Sprintf(
"Problem opening the %q message file for unpacking: %s",
eml,
err.Error()))
return
}
partsIterate(msg.Header, msg.Body, cutExt(eml), errors)
}