-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsendmail.go
91 lines (73 loc) · 1.59 KB
/
sendmail.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
package sendmail
import (
"encoding/json"
"fmt"
"io"
"net/mail"
gomail "github.com/go-mail/mail"
)
type Config struct {
Server string `json:"server"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
}
func (c *Config) Update(n *Config) {
if n.Server != "" {
c.Server = n.Server
}
if n.Port != 0 {
c.Port = n.Port
}
if n.User != "" {
c.User = n.User
c.Password = n.Password
}
}
func NewConfig(r io.Reader) (*Config, error) {
c := Config{
Server: "",
Port: 465,
User: "",
Password: "",
}
if err := json.NewDecoder(r).Decode(&c); err != nil {
err = fmt.Errorf("Failed to decode JSON: %v", err)
return &c, err
}
return &c, nil
}
func NewMail(from *string, to, cc []*mail.Address, subject, body, attachment string, html bool) *gomail.Message {
var toAddr, ccAddr []string
m := gomail.NewMessage()
m.SetHeader("From", *from)
for _, t := range to {
toAddr = append(toAddr, m.FormatAddress(t.Address, t.Name))
}
m.SetHeader("To", toAddr...)
if len(cc) != 0 {
for _, c := range to {
ccAddr = append(toAddr, m.FormatAddress(c.Address, c.Name))
}
m.SetHeader("Cc", ccAddr...)
}
m.SetHeader("Subject", subject)
if html == true {
m.SetBody("text/html", body)
} else {
m.SetBody("text/plain", body)
}
if attachment != "" {
m.Attach(attachment)
}
return m
}
func Send(m *gomail.Message, c *Config) error {
var d *gomail.Dialer
if c.User == "" {
d = &gomail.Dialer{Host: c.Server, Port: c.Port}
} else {
d = gomail.NewDialer(c.Server, c.Port, c.User, c.Password)
}
return d.DialAndSend(m)
}