-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmail.go
92 lines (74 loc) · 1.86 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package mailer
import (
"bufio"
"bytes"
"encoding/base64"
"fmt"
"strings"
)
// Mail struct represents an e-Mail
type Mail struct {
// Sender Name
FromName string
// Sender email address
From string
// List of recipients
To []string
Cc []string
Bcc []string
// Mail subject as UTF-8 string
Subject string
// Headers are the headers
Headers map[string]string
// Body provides the actual body of the mail.
// It has to be UTF-8 encoded, or you must set the Content-Type Header
Body string
}
// NewMail returns a new Mail struct with initialized headers
func NewMail() *Mail {
m := new(Mail)
m.Headers = make(map[string]string)
m.SetHeader("MIME-Version", "1.0")
m.SetHeader("Content-Type", "text/html; charset=\"utf-8\"")
m.SetHeader("Content-Transfer-Encoding", "base64")
return m
}
// SetTo sets mail TO recepients
func (m *Mail) SetTo(addresses ...string) {
m.To = sliceIt(m.To, addresses)
}
// SetCc sets mail CC recepients
func (m *Mail) SetCc(addresses ...string) {
m.Cc = sliceIt(m.Cc, addresses)
}
// SetBcc sets mail BCC recepients
func (m *Mail) SetBcc(addresses ...string) {
m.Bcc = sliceIt(m.Bcc, addresses)
}
// SetHeader sets mail custom headers
func (m *Mail) SetHeader(k, v string) {
m.Headers[k] = v
}
func sliceIt(slice, add []string) []string {
if len(slice) == 0 {
return add
}
for _, a := range add {
slice = append(slice, a)
}
return slice
}
// Raw returns a raw message content according to RFC 822-style
func (m *Mail) Raw() []byte {
var message bytes.Buffer
w := bufio.NewWriter(&message)
fmt.Fprintf(w, "From: %s <%s>\r\n", m.FromName, m.From)
fmt.Fprintf(w, "To: %s\r\n", strings.Join(m.To, ","))
for k, v := range m.Headers {
fmt.Fprintf(w, "%s: %s\r\n", k, v)
}
fmt.Fprintf(w, "Subject: %s\r\n\r\n%s\r\n", m.Subject,
base64.StdEncoding.EncodeToString([]byte(m.Body)))
w.Flush()
return message.Bytes()
}