-
Notifications
You must be signed in to change notification settings - Fork 75
/
mailyak.go
230 lines (201 loc) · 5.86 KB
/
mailyak.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package mailyak
import (
"bytes"
"crypto/tls"
"fmt"
"net/mail"
"net/smtp"
"regexp"
"strings"
"time"
)
// MailYak is an easy-to-use email builder.
type MailYak struct {
html BodyPart
plain BodyPart
localName string
toAddrs []string
ccAddrs []string
bccAddrs []string
subject string
fromAddr string
fromName string
replyTo string
headers map[string][]string // arbitrary headers
attachments []attachment
trimRegex *regexp.Regexp
auth smtp.Auth
host string
sender emailSender
writeBccHeader bool
date string
}
// Email Date timestamp format
const mailDateFormat = time.RFC1123Z
// New returns an instance of MailYak using host as the SMTP server, and
// authenticating with auth if non-nil.
//
// host must include the port number (i.e. "smtp.itsallbroken.com:25")
//
// mail := mailyak.New("smtp.itsallbroken.com:25", smtp.PlainAuth(
// "",
// "username",
// "password",
// "smtp.itsallbroken.com",
// ))
//
// MailYak instances created with New will switch to using TLS after connecting
// if the remote host supports the STARTTLS command. For an explicit TLS
// connection, or to provide a custom tls.Config, use NewWithTLS() instead.
func New(host string, auth smtp.Auth) *MailYak {
return &MailYak{
headers: map[string][]string{},
host: host,
auth: auth,
sender: newSenderWithStartTLS(host),
trimRegex: regexp.MustCompile("\r?\n"),
writeBccHeader: false,
date: time.Now().Format(mailDateFormat),
}
}
// NewWithTLS returns an instance of MailYak using host as the SMTP server over
// an explicit TLS connection, and authenticating with auth if non-nil.
//
// host must include the port number (i.e. "smtp.itsallbroken.com:25")
//
// mail := mailyak.NewWithTLS("smtp.itsallbroken.com:25", smtp.PlainAuth(
// "",
// "username",
// "password",
// "smtp.itsallbroken.com",
// ), tlsConfig)
//
// If tlsConfig is nil, a sensible default is generated that can connect to
// host.
func NewWithTLS(host string, auth smtp.Auth, tlsConfig *tls.Config) (*MailYak, error) {
// Construct a default MailYak instance
m := New(host, auth)
// Initialise the TLS sender with the (potentially nil) TLS config, swapping
// it with the default STARTTLS sender.
var err error
m.sender, err = newSenderWithExplicitTLS(host, tlsConfig)
if err != nil {
return nil, err
}
return m, nil
}
// Send attempts to send the built email via the configured SMTP server.
//
// Attachments are read and the email timestamp is created when Send() is
// called, and any connection/authentication errors will be returned by Send().
func (m *MailYak) Send() error {
m.date = time.Now().Format(mailDateFormat)
return m.sender.Send(m)
}
// MimeBuf returns the buffer containing all the RAW MIME data.
//
// MimeBuf is typically used with an API service such as Amazon SES that does
// not use an SMTP interface.
func (m *MailYak) MimeBuf() (*bytes.Buffer, error) {
m.date = time.Now().Format(mailDateFormat)
buf := &bytes.Buffer{}
if err := m.buildMime(buf); err != nil {
return nil, err
}
return buf, nil
}
// String returns a redacted description of the email state, typically for
// logging or debugging purposes.
//
// Authentication information is not included in the returned string.
func (m *MailYak) String() string {
var (
att []string
custom string
)
for _, a := range m.attachments {
att = append(att, "{filename: "+a.filename+"}")
}
if len(m.headers) > 0 {
var hdrs []string
for k, v := range m.headers {
hdrs = append(hdrs, fmt.Sprintf("%s: %q", k, v))
}
custom = strings.Join(hdrs, ", ") + ", "
}
_, isTLSSender := m.sender.(*senderExplicitTLS)
return fmt.Sprintf(
"&MailYak{date: %q, from: %q, fromName: %q, html: %v bytes, plain: %v bytes, toAddrs: %v, "+
"bccAddrs: %v, subject: %q, %vhost: %q, attachments (%v): %v, auth set: %v, explicit tls: %v}",
m.date,
m.fromAddr,
m.fromName,
len(m.HTML().String()),
len(m.Plain().String()),
m.toAddrs,
m.bccAddrs,
m.subject,
custom,
m.host,
len(att),
att,
m.auth != nil,
isTLSSender,
)
}
// HTML returns a BodyPart for the HTML email body.
func (m *MailYak) HTML() *BodyPart {
return &m.html
}
// Plain returns a BodyPart for the plain-text email body.
func (m *MailYak) Plain() *BodyPart {
return &m.plain
}
// getLocalName should return the sender domain to be used in the EHLO/HELO
// command.
func (m *MailYak) getLocalName() string {
return m.localName
}
// getToAddrs should return a slice of email addresses to be added to the
// RCPT TO command.
func (m *MailYak) getToAddrs() []string {
// Pre-allocate the slice to avoid growing it, we already know how big it
// needs to be.
addrs := len(m.toAddrs) + len(m.ccAddrs) + len(m.bccAddrs)
out := make([]string, 0, addrs)
out = append(out, stripNames(m.toAddrs)...)
out = append(out, stripNames(m.ccAddrs)...)
out = append(out, stripNames(m.bccAddrs)...)
return out
}
// getFromAddr should return the address to be used in the MAIL FROM
// command.
func (m *MailYak) getFromAddr() string {
return m.fromAddr
}
// getAuth should return the smtp.Auth if configured, nil if not.
func (m *MailYak) getAuth() smtp.Auth {
return m.auth
}
// stripNames returns a new slice with only the email parts from the RFC 5322 addresses.
//
// Or in other words, converts:
// ["[email protected]", "John <[email protected]>", "invalid"]
// to
// ["[email protected]", "[email protected]", "invalid"].
//
// Note that invalid addresses are kept as they are.
func stripNames(addresses []string) []string {
result := make([]string, 0, len(addresses))
for _, original := range addresses {
addr, err := mail.ParseAddress(original)
if err != nil {
// add as it is
result = append(result, original)
} else {
// add only the email part
result = append(result, addr.Address)
}
}
return result
}