forked from nymsio/pgpmail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.go
110 lines (95 loc) · 2.18 KB
/
message.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
package pgpmail
import (
"bytes"
"fmt"
)
var crlf = []byte("\r\n")
type Header struct {
Name string
Value string
}
func (h Header) String() string {
return fmt.Sprintf("%s: %s", h.Name, h.Value)
}
// A MessagePart represents either an entire message or a multipart section.
type MessagePart struct {
rawContent []byte
// HeaderList contains Header values in the order in which they appear in the message
HeaderList []*Header
Body string
}
type Message struct {
MessagePart
ctPrimary string
ctSecondary string
ctParams map[string]string
mpContent *multipartContent
}
func ParseMessage(msg string) (*Message, error) {
return NewReader(msg).ReadMessage()
}
func (m *MessagePart) String() string {
b := new(bytes.Buffer)
for _, h := range m.HeaderList {
b.WriteString(h.String())
b.Write(crlf)
}
b.Write(crlf)
b.WriteString(m.Body)
return b.String()
}
func (m *MessagePart) AddHeader(name, value string) {
key := CanonicalMIMEHeaderKey(name)
m.HeaderList = append(m.HeaderList, &Header{key, value})
}
func (m *MessagePart) SetHeader(name, value string) {
h := m.findFirstHeader(name)
if h == nil {
m.AddHeader(name, value)
} else {
h.Value = value
}
}
// RemoveHeader removes all headers matching name and returns Value of
// the first one discovered. Returns "" if no such header exists
func (m *MessagePart) RemoveHeader(name string) string {
h := m.findFirstHeader(name)
if h == nil {
return ""
}
newHdrs := make([]*Header, 0, len(m.HeaderList)-1)
key := CanonicalMIMEHeaderKey(name)
for _, h := range m.HeaderList {
if h.Name != key {
newHdrs = append(newHdrs, h)
}
}
m.HeaderList = newHdrs
return h.Value
}
func (m *MessagePart) GetHeaderValue(name string) string {
h := m.findFirstHeader(name)
if h == nil {
return ""
}
return h.Value
}
func (m *MessagePart) findFirstHeader(name string) *Header {
key := CanonicalMIMEHeaderKey(name)
for _, h := range m.HeaderList {
if h.Name == key {
return h
}
}
return nil
}
func (m *MessagePart) GetHeaders(name string) []string {
key := CanonicalMIMEHeaderKey(name)
ret := []string{}
for _, h := range m.HeaderList {
if h.Name == key {
ret = append(ret, h.Value)
}
}
return ret
}