forked from sanbornm/mp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mp.go
87 lines (72 loc) · 1.64 KB
/
mp.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/mail"
"os"
"github.com/jhillyerd/go.enmime"
)
type Attachment struct {
ContentType string
Filename string
Disposition string
}
type Email struct {
Text string
Html string
Headers map[string]string
From []*mail.Address
To []*mail.Address
Cc []*mail.Address
Priority string
Attachments []Attachment
}
func StreamToString(stream io.Reader) string {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf.String()
}
func ParseEmail(content string) Email {
email := Email{}
msg, err := mail.ReadMessage(bytes.NewBuffer([]byte(content)))
if err != nil {
return email
}
mime, _ := enmime.ParseMIMEBody(msg)
headers := map[string]string{}
for key, values := range msg.Header {
headers[key] = values[0]
}
fromAddrs, _ := msg.Header.AddressList("From")
toAddrs, _ := msg.Header.AddressList("To")
ccAddrs, _ := msg.Header.AddressList("Cc")
var attachments []Attachment
for _, attach := range mime.Attachments {
a := Attachment{}
a.ContentType = attach.ContentType()
a.Filename = attach.FileName()
a.Disposition = attach.Disposition()
attachments = append(attachments, a)
}
return Email{
Html: mime.HTML,
Text: mime.Text,
Headers: headers,
Priority: "normal",
From: fromAddrs,
To: toAddrs,
Cc: ccAddrs,
Attachments: attachments}
}
func main() {
bytes, _ := ioutil.ReadAll(os.Stdin)
email := ParseEmail(string(bytes))
b, err := json.MarshalIndent(email, "", " ")
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
}