-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailer.go
112 lines (94 loc) · 2.26 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
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
package lib
import (
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net/mail"
"net/smtp"
"os"
"strconv"
)
// MailConfig represents SMTP server details
type MailConfig struct {
From string `json:"from"`
To string `json:"to"`
ServerHost string `json:"serverHost"`
ServerPort int `json:"serverPort"`
ServerUser string `json:"serverUser"`
ServerPassword string `json:"serverPassword"`
}
// LoadMailConfig reads mail configuration from file
func LoadMailConfig(path string) (*MailConfig, error) {
m := &MailConfig{}
file, err := os.Open(path)
defer file.Close()
if err != nil {
return m, err
}
dec := json.NewDecoder(file)
err = dec.Decode(m)
return m, err
}
// SendMailSSL sends a mail message using SMTP servers
// that require a SSL connection from the very beginning.
func SendMailSSL(cfg *MailConfig, subject string, body string) error {
from := mail.Address{Address: cfg.From}
to := mail.Address{Address: cfg.To}
// Setup headers
headers := make(map[string]string)
headers["From"] = from.String()
headers["To"] = to.String()
headers["Subject"] = subject
// Setup message
message := ""
for k, v := range headers {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + body
// Connect to the SMTP Server
auth := smtp.PlainAuth("", cfg.ServerUser, cfg.ServerPassword, cfg.ServerHost)
// TLS config
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: cfg.ServerHost,
}
// Here is the key, you need to call tls.Dial instead of smtp.Dial
// for smtp servers running on 465 that require an ssl connection
// from the very beginning (no starttls)
serverHostPort := cfg.ServerHost + ":" + strconv.Itoa(cfg.ServerPort)
conn, err := tls.Dial("tcp", serverHostPort, tlsConfig)
if err != nil {
return err
}
c, err := smtp.NewClient(conn, cfg.ServerHost)
if err != nil {
log.Panic(err)
}
// Auth
if err = c.Auth(auth); err != nil {
return err
}
// To && From
if err = c.Mail(from.Address); err != nil {
return err
}
if err = c.Rcpt(to.Address); err != nil {
return err
}
// Data
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
}
c.Quit()
return nil
}