forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.go
98 lines (81 loc) · 1.61 KB
/
connection.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
package mail
import (
"crypto/tls"
"fmt"
"net"
"net/smtp"
)
// Transport initialize the smtp client
func Transport(address string, port int, host string, a smtp.Auth) (*smtp.Client, error) {
addr := fmt.Sprintf("%s:%d", address, port)
var conn net.Conn
conn, err := tls.Dial("tcp", addr, nil) // some smtp servers require TLS handshake
if err != nil {
conn, err = net.Dial("tcp", addr) // fall back
if err != nil {
return nil, err
}
}
c, err := smtp.NewClient(conn, address)
if err != nil {
return nil, err
}
if host != "" {
if err := c.Hello(host); err != nil {
return nil, err
}
}
if ok, _ := c.Extension("STARTTLS"); ok {
config := &tls.Config{
InsecureSkipVerify: true,
}
if err = c.StartTLS(config); err != nil {
return nil, err
}
}
if a != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(a); err != nil {
return nil, err
}
}
}
return c, nil
}
// Send send message through the client
func Send(c *smtp.Client, message *Message) (err error) {
data, err := message.RenderData()
if err != nil {
return
}
if err = c.Reset(); err != nil {
return
}
if err = c.Mail(message.From); err != nil {
return
}
if err = addRcpt(c, message.To); err != nil {
return
}
if err = addRcpt(c, message.Cc); err != nil {
return
}
if err = addRcpt(c, message.Bcc); err != nil {
return
}
w, err := c.Data()
if err != nil {
return
}
defer w.Close()
_, err = w.Write(data)
return
}
func addRcpt(c *smtp.Client, address []string) error {
for _, addr := range address {
if err := c.Rcpt(addr); err != nil {
return err
}
}
return nil
}