-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmail.go
75 lines (60 loc) · 1.62 KB
/
mail.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
package gomail
import (
"fmt"
"io"
"io/ioutil"
"net/mail"
"strings"
)
type Message struct {
Header mail.Header
Body string
}
// ReadMessage reads the message and returns the Message value
func ReadMessage(src io.Reader) (Message, error) {
// Read message to parse out Header/Body
m, err := mail.ReadMessage(src)
if err != nil {
return Message{}, err
}
body, err := ioutil.ReadAll(m.Body)
if err != nil {
return Message{Header: m.Header}, err
}
return Message{
Header: m.Header,
Body: string(body),
}, nil
}
// AppendHeader adds the new entry to the message header
func (m *Message) AppendHeader(entry HeaderEntry) error {
keyExists := m.keyExists(entry.Key)
if !multipleFieldsAllowed(entry.Key) && keyExists {
return fmt.Errorf("key %s already exists in header", entry.Key)
}
// multiple fields are allowed so we can append if it exists
if keyExists {
s := strings.Join(entry.Value, ", ")
newValue := []string{fmt.Sprintf("%s, %s", m.Header[entry.Key], s)}
m.Header[entry.Key] = newValue
return nil
}
m.Header[entry.Key] = entry.Value
return nil
}
// Join appends the body of the message to the header to display the full
// message
func (m *Message) Join() string {
var result []string
for key, value := range m.Header {
// value is stored as a slice within the first element
result = append(result, fmt.Sprintf("%s: %s", key, value[0]))
}
// Ensure there's a blank line before starting the body of the message
result = append(result, "")
result = append(result, m.Body)
return strings.Join(result, "\r\n")
}
func (m *Message) keyExists(key string) bool {
return m.Header.Get(key) != ""
}