-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathemail.go
340 lines (289 loc) · 7.62 KB
/
email.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Copyright (c) 2014-2019 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package goemail
import (
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"net"
"net/mail"
"net/smtp"
"net/url"
"os"
"strings"
"time"
)
// Define errors
var (
ErrInvalidScheme = errors.New("invalid scheme")
ErrNoRecipients = errors.New("no recipients specified")
)
// Message defines an email message, headers, and attachments.
type Message struct {
from string
name string
to []string
cc []string
bcc []string
date string
subject string
body string
bodyContentType string
attachments map[string][]byte
}
// SMTP defines and smtp server along with the auth info.
type SMTP struct {
scheme string
server string
auth *smtp.Auth
hostname string
tlsConfig *tls.Config
}
func newMessage(from, subject, body, contenttype string) *Message {
m := Message{
from: from,
subject: subject,
date: time.Now().Format(time.RFC1123Z),
body: body,
bodyContentType: contenttype,
attachments: make(map[string][]byte),
}
return &m
}
// NewMessageType creates a new email with the specified content-type.
func NewMessageType(from, subject, body, contentType string) *Message {
// Allow addresses of the form "Alice <[email protected]>".
fromAddr, err := mail.ParseAddress(from)
if err != nil {
return nil
}
// Create the message with the parsed from address.
m := newMessage(fromAddr.Address, subject, body, contentType)
// Set the sender's display name.
if fromAddr.Name != "" {
m.SetName(fromAddr.Name)
}
return m
}
// NewMessage creates a new text/plain email.
func NewMessage(from, subject, body string) *Message {
return NewMessageType(from, subject, body, "text/plain")
}
// NewHTMLMessage creates a new text/html email.
func NewHTMLMessage(from, subject, body string) *Message {
return NewMessageType(from, subject, body, "text/html")
}
// AddAttachment adds the provided attachment to the message.
func (m *Message) AddAttachment(filename string, attachment []byte) {
m.attachments[filename] = attachment
}
// AddAttachmentFromFile adds an attachment specified by filename to the
// message.
func (m *Message) AddAttachmentFromFile(filename string) error {
a, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
m.attachments[filename] = a
return nil
}
// IsValidAddress validates the input email address, returning false if the
// address cannot be parsed by mail.ParseAddress.
func IsValidAddress(addr string) bool {
_, err := mail.ParseAddress(addr)
return err == nil
}
// AddCC adds a single email address to the CC list.
func (m *Message) AddCC(emailAddr string) {
m.cc = append(m.cc, emailAddr)
}
// AddBCC adds a single email address to the BCC list.
func (m *Message) AddBCC(emailAddr string) {
m.bcc = append(m.bcc, emailAddr)
}
// AddTo adds an email address to the To recipients.
func (m *Message) AddTo(emailAddr string) {
m.to = append(m.to, emailAddr)
}
// Body returns the formatted message body.
func (m *Message) Body() []byte {
buf := bytes.NewBuffer(nil)
from := fmt.Sprintf("\"%s\" <%s>", m.name, m.from)
buf.WriteString("From: " + from + "\n")
buf.WriteString("Date: " + m.date + "\n")
buf.WriteString("To: " + strings.Join(m.to, ",") + "\n")
if len(m.cc) > 0 {
buf.WriteString("Cc: " + strings.Join(m.cc, ",") + "\n")
}
buf.WriteString("Subject: " + m.subject + "\n")
buf.WriteString("MIME-Version: 1.0\n")
boundary := "mnwKuycHoXCwn9S5UY6avz8ZGJPEeUdMPS"
if len(m.attachments) > 0 {
buf.WriteString("Content-Type: multipart/mixed; boundary=" + boundary + "\n")
buf.WriteString("--" + boundary + "\n")
}
buf.WriteString(fmt.Sprintf("Content-Type: %s; charset=utf-8\n", m.bodyContentType))
// Empty line must precede the body.
buf.WriteString("\n")
buf.WriteString(m.body)
if len(m.attachments) > 0 {
for k, v := range m.attachments {
buf.WriteString("\n\n--" + boundary + "\n")
buf.WriteString("Content-Type: application/octet-stream\n")
buf.WriteString("Content-Transfer-Encoding: base64\n")
buf.WriteString("Content-Disposition: attachment; filename=\"" + k + "\"\n\n")
b64 := make([]byte, base64.StdEncoding.EncodedLen(len(v)))
base64.StdEncoding.Encode(b64, v)
buf.Write(b64)
buf.WriteString("\n--" + boundary)
}
buf.WriteString("--")
}
return buf.Bytes()
}
// From returns the sender's email address
func (m *Message) From() string {
return m.from
}
// Name returns the sender's display name.
func (m *Message) Name() string {
return m.name
}
// SetName sets the sender's display name.
func (m *Message) SetName(name string) {
m.name = name
}
// Recipients returns an array of all the recipients, which includes
// To, CC, and BCC
func (m *Message) Recipients() []string {
rcpts := make([]string, 0, len(m.to)+len(m.cc)+len(m.bcc))
rcpts = append(rcpts, m.to...)
rcpts = append(rcpts, m.cc...)
rcpts = append(rcpts, m.bcc...)
return rcpts
}
// NewSMTP is called with smtp[s]://[username:[password]]@server:[port]
func NewSMTP(rawURL string, tlsConfig *tls.Config) (*SMTP, error) {
url, err := url.Parse(rawURL)
if err != nil {
return nil, err
}
switch url.Scheme {
case "smtp":
break
case "smtps":
fallthrough
case "tls":
if tlsConfig != nil && tlsConfig.ServerName == "" {
tlsConfig.ServerName = url.Host
}
default:
return nil, ErrInvalidScheme
}
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
mysmtp := &SMTP{
scheme: url.Scheme,
hostname: hostname,
tlsConfig: tlsConfig,
}
_, _, err = net.SplitHostPort(url.Host)
if err != nil {
mysmtp.server = url.Host + ":25"
} else {
mysmtp.server = url.Host
}
if url.User != nil {
p, _ := url.User.Password()
// - put host:port in the fourth argument here as there is a "wrong host name"
// check in go SMTP library auth.go, May have better solution but need
// to understand the purpose of the check
a := smtp.PlainAuth("", url.User.Username(), p, mysmtp.server)
mysmtp.auth = &a
}
return mysmtp, nil
}
// Send connects to the server and sends the email message.
func (s *SMTP) Send(msg *Message) error {
var conn net.Conn
var err error
var success bool
recipients := msg.Recipients()
if len(recipients) < 1 {
return ErrNoRecipients
}
switch s.scheme {
case "smtps":
conn, err = tls.Dial("tcp", s.server, s.tlsConfig)
case "tls":
fallthrough
default:
conn, err = net.Dial("tcp", s.server)
}
if err != nil {
return err
}
client, err := smtp.NewClient(conn, s.server)
if err != nil {
return err
}
defer func() {
if !success {
client.Quit()
}
}()
// Send HELO/EHLO
if err = client.Hello(s.hostname); err != nil {
return err
}
// Check if STARTTLS is supported if not smtps.
if s.scheme != "smtps" {
hasStartTLS, _ := client.Extension("STARTTLS")
if !hasStartTLS && s.scheme == "tls" {
return fmt.Errorf("server does not support TLS")
}
if hasStartTLS {
if err = client.StartTLS(s.tlsConfig); err != nil {
return err
}
}
}
// Send authentication, if specified
if s.auth != nil {
if err = client.Auth(*s.auth); err != nil {
return err
}
}
// MAIL FROM
if err = client.Mail(msg.From()); err != nil {
return err
}
// RCPT TO
for _, rcpt := range msg.Recipients() {
if err = client.Rcpt(rcpt); err != nil {
return err
}
}
// DATA
dataBuf, err := client.Data()
if err != nil {
return err
}
_, err = dataBuf.Write(msg.Body())
dataBuf.Close()
if err != nil {
return err
}
err = client.Quit()
if err != nil {
return err
}
success = true
return nil
}