This repository has been archived by the owner on Feb 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
envelope.go
101 lines (86 loc) · 2.34 KB
/
envelope.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
package gosmtp
import (
"bufio"
"bytes"
"errors"
"net/mail"
)
// Envelope represents a message envelope
type Envelope struct {
MailFrom *mail.Address // Envelope sender
MailTo []*mail.Address // Envelope recipients
Mail *mail.Message // Final message
Priority int
data *bytes.Buffer // data stores the header and message body
headers map[string]string // New headers added by server
}
func NewEnvelope() *Envelope {
return &Envelope{
MailTo: []*mail.Address{},
data: bytes.NewBufferString(""),
headers: make(map[string]string),
}
}
// Close the envelope before handing it futher
func (e *Envelope) Close() (err error) {
e.Mail, err = mail.ReadMessage(bufio.NewReader(e.data))
if err != nil {
return
}
for headerKey, headerValue := range e.headers {
if e.Mail.Header.Get(headerKey) != "" {
e.Mail.Header[headerKey] = append(e.Mail.Header[headerKey], headerValue)
} else {
e.Mail.Header[headerKey] = []string{headerValue}
}
}
return
}
// IsSet returns if the envelope is set
func (e *Envelope) IsSet() bool {
return e.MailFrom != nil
}
// Reader returns reader for envelope data
func (e *Envelope) Reader() *bytes.Reader {
return bytes.NewReader(e.data.Bytes())
}
func (e *Envelope) Bytes() []byte {
return e.data.Bytes()
}
// Reset resets envelope to initial state
func (e *Envelope) Reset() error {
e.MailTo = []*mail.Address{}
e.MailFrom = nil
if e.data != nil {
e.data.Reset()
}
for key, _ := range e.headers {
delete(e.headers, key)
}
return nil
}
// AddRecipient adds recipient to envelope recipients
// returns error if maximum number of recipients is reached
func (e *Envelope) AddRecipient(rcpt *mail.Address) error {
e.MailTo = append(e.MailTo, rcpt)
return nil
}
func (e *Envelope) BeginData() error {
if len(e.MailTo) == 0 {
return errors.New("554 5.5.1 Error: no valid recipients")
}
e.data = bytes.NewBuffer([]byte{})
return nil
}
// Write writes bytes into the envelope buffer
func (e *Envelope) Write(line []byte) (int, error) {
return e.data.Write(line)
}
// WriteString writes string into the envelope buffer
func (e *Envelope) WriteString(line string) (int, error) {
return e.data.WriteString(line)
}
// WriteLine writes data into the envelope followed by new line
func (e *Envelope) WriteLine(line []byte) (int, error) {
return e.data.Write(append(line, []byte("\r\n")...))
}