-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailer.go
85 lines (67 loc) · 1.36 KB
/
mailer.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
package main
import (
"crypto/tls"
"fmt"
"net"
netmail "net/mail"
"net/smtp"
)
type Mailer struct {
mailsrv, mailfrom, mailpass string
}
func NewMailer(mailsrv, mailfrom, mailpass string) *Mailer {
return &Mailer{
mailsrv: mailsrv,
mailfrom: mailfrom,
mailpass: mailpass,
}
}
func (m *Mailer) Send(email, subj, body string) error {
from := netmail.Address{"", m.mailfrom}
to := netmail.Address{"", email}
headers := make(map[string]string)
headers["From"] = from.String()
headers["To"] = to.String()
headers["Subject"] = subj
message := ""
for k, v := range headers {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + body
host, _, _ := net.SplitHostPort(m.mailsrv)
auth := smtp.PlainAuth("", m.mailfrom, m.mailpass, host)
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: host,
}
conn, err := tls.Dial("tcp", m.mailsrv, tlsconfig)
if err != nil {
return err
}
c, err := smtp.NewClient(conn, host)
if err != nil {
return err
}
if err = c.Auth(auth); err != nil {
return err
}
if err = c.Mail(from.Address); err != nil {
return err
}
if err = c.Rcpt(to.Address); err != nil {
return err
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write([]byte(message))
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
}