This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
smtp.go
104 lines (83 loc) · 1.81 KB
/
smtp.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
package gophermail
import (
"crypto/tls"
"net/smtp"
)
// SendMail connects to the server at addr, switches to TLS if possible,
// authenticates with mechanism a if possible, and then sends the given Message.
//
// Based heavily on smtp.SendMail().
func SendMail(addr string, a smtp.Auth, msg *Message) error {
msgBytes, err := msg.Bytes()
if err != nil {
return err
}
var to []string
for _, address := range msg.To {
to = append(to, address.Address)
}
for _, address := range msg.Cc {
to = append(to, address.Address)
}
for _, address := range msg.Bcc {
to = append(to, address.Address)
}
return smtp.SendMail(addr, a, msg.From.Address, to, msgBytes)
}
// SendTLSMail does the same thing as SendMail, except with the added
// option of providing a tls.Config
func SendTLSMail(addr string, a smtp.Auth, msg *Message, cfg tls.Config) error {
msgBytes, err := msg.Bytes()
if err != nil {
return err
}
var to []string
for _, address := range msg.To {
to = append(to, address.Address)
}
for _, address := range msg.Cc {
to = append(to, address.Address)
}
for _, address := range msg.Bcc {
to = append(to, address.Address)
}
from := msg.From.String()
c, err := smtp.Dial(addr)
if err != nil {
return err
}
defer c.Close()
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(&cfg); err != nil {
return err
}
}
if a != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(a); err != nil {
return err
}
}
}
if err = c.Mail(from); err != nil {
return err
}
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write(msgBytes)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
}