-
Notifications
You must be signed in to change notification settings - Fork 0
/
smtp.go
90 lines (76 loc) · 1.67 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
package main
import (
"crypto/tls"
"fmt"
"net/smtp"
"text/template"
log "github.com/sirupsen/logrus"
)
func SendMail(config *Config, templateFile string, templateData any) error {
address := fmt.Sprintf("%s:%d", config.Host, config.Port)
log.Debugf("Dial %s \n", address)
connection, err := tls.Dial("tcp", address, &tls.Config{
ServerName: config.Host,
})
if err != nil {
return err
}
defer connection.Close()
log.Debugf("Connect %s \n", address)
client, err := smtp.NewClient(connection, config.Host)
if err != nil {
return err
}
defer client.Quit()
log.Debug("Auth")
auth := smtp.PlainAuth("", config.User, config.Pass, config.Host)
err = client.Auth(auth)
if err != nil {
return err
}
log.Debug("Template")
tmpl, err := template.ParseFiles(templateFile)
if err != nil {
return err
}
for i, rcpt := range config.To {
log.Debugf("Mail %d \n", i)
log.Debugf(" From %s \n", config.From)
err = client.Mail(config.From)
if err != nil {
return err
}
log.Debugf(" To %s \n", rcpt)
err = client.Rcpt(rcpt)
if err != nil {
return err
}
log.Debug(" Send")
w, err := client.Data()
if err != nil {
return err
}
log.Debug(" Headers")
headers := make(map[string]string)
headers["From"] = config.From
headers["To"] = rcpt
headers["Subject"] = config.Subject
headers["Content-Type"] = "text/plain; charset=\"UTF-8\""
for k, v := range headers {
_, err = w.Write([]byte(fmt.Sprintf("%s: %s\r\n", k, v)))
if err != nil {
return err
}
}
log.Debug(" Body")
err = tmpl.Execute(w, templateData)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
}
return nil
}