forked from dexidp/dex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smtp.go
84 lines (72 loc) · 1.71 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
package email
import (
"encoding/json"
"errors"
"gopkg.in/gomail.v2"
)
const (
SmtpEmailerType = "smtp"
)
func init() {
RegisterEmailerConfigType(SmtpEmailerType, func() EmailerConfig { return &SmtpEmailerConfig{} })
}
type SmtpEmailerConfig struct {
Host string `json:"host"`
Port int `json:"port"`
Auth string `json:"auth"`
Username string `json:"username"`
Password string `json:"password"`
}
func (cfg SmtpEmailerConfig) EmailerType() string {
return SmtpEmailerType
}
func (cfg SmtpEmailerConfig) EmailerID() string {
return SmtpEmailerType
}
func (cfg SmtpEmailerConfig) Emailer() (Emailer, error) {
var dialer *gomail.Dialer
if cfg.Auth == "plain" {
dialer = gomail.NewPlainDialer(cfg.Host, cfg.Port, cfg.Username, cfg.Password)
} else {
dialer = &gomail.Dialer{
Host: cfg.Host,
Port: cfg.Port,
}
}
return &smtpEmailer{
dialer: dialer,
}, nil
}
type smtpEmailerConfig SmtpEmailerConfig
func (cfg *SmtpEmailerConfig) UnmarshalJSON(data []byte) error {
smtpCfg := smtpEmailerConfig{}
err := json.Unmarshal(data, &smtpCfg)
if err != nil {
return err
}
if smtpCfg.Host == "" {
return errors.New("must set SMTP host")
}
if smtpCfg.Port == 0 {
return errors.New("must set SMTP port")
}
*cfg = SmtpEmailerConfig(smtpCfg)
return nil
}
type smtpEmailer struct {
dialer *gomail.Dialer
}
func (emailer *smtpEmailer) SendMail(from, subject, text, html string, to ...string) error {
msg := gomail.NewMessage()
msg.SetHeader("From", from)
msg.SetHeader("To", to...)
msg.SetHeader("Subject", subject)
msg.SetBody("text/plain", text)
msg.SetBody("text/html", html)
err := emailer.dialer.DialAndSend(msg)
if err != nil {
counterEmailSendErr.Add(1)
return err
}
return nil
}