-
Notifications
You must be signed in to change notification settings - Fork 5
/
quickmail.go
86 lines (76 loc) · 1.44 KB
/
quickmail.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
// vim: tabstop=2 shiftwidth=2
package quickmail
import (
"bytes"
"errors"
"fmt"
"os"
)
type message struct {
headers map[string]string
Prefix string
Filename string
Items []string
Suffix string
}
func NewMessage() *message {
return &message{headers: make(map[string]string)}
}
func (m message) Set(head, content string) {
m.headers[head] = content
}
func (m message) Get(head string) string {
return m.headers[head]
}
func (m message) Del(head string) {
delete(m.headers, head)
}
func (m *message) Text(t string) {
m.Prefix += t
}
func (m *message) List(l []string) {
m.Items = l
}
func (m message) Compile() (b []byte, err error) {
var ok bool
_, ok = m.headers["From"]
if !ok {
err = errors.New("Compulsory From header not defined")
return
}
_, ok = m.headers["To"]
if !ok {
err = errors.New("Compulsory To header not defined")
return
}
buf := new(bytes.Buffer)
for h := range m.headers {
buf.WriteString(fmt.Sprintf("%s: %s\n", h, m.headers[h]))
}
buf.WriteString("\n")
if m.Prefix != "" {
buf.WriteString(m.Prefix)
buf.WriteString("\n")
}
if m.Filename != "" {
var f *os.File
f, err = os.Open(m.Filename)
if err != nil {
return
}
defer f.Close()
_, err = buf.ReadFrom(f)
buf.WriteString("\n")
}
if len(m.Items) > 0 {
for _, entry := range m.Items {
buf.WriteString(entry + "\n")
}
}
if m.Suffix != "" {
buf.WriteString(m.Suffix)
buf.WriteString("\n")
}
b = buf.Bytes()
return
}