dex/email/mailgun.go

94 lines
1.9 KiB
Go
Raw Normal View History

2015-08-18 05:57:27 +05:30
package email
import (
"encoding/json"
"errors"
"github.com/coreos/dex/pkg/log"
mailgun "github.com/mailgun/mailgun-go"
)
const (
MailgunEmailerType = "mailgun"
)
func init() {
RegisterEmailerConfigType(MailgunEmailerType, func() EmailerConfig { return &MailgunEmailerConfig{} })
}
type MailgunEmailerConfig struct {
FromAddr string `json:"from"`
2015-08-18 05:57:27 +05:30
PrivateAPIKey string `json:"privateAPIKey"`
PublicAPIKey string `json:"publicAPIKey"`
Domain string `json:"domain"`
}
func (cfg MailgunEmailerConfig) EmailerType() string {
return MailgunEmailerType
}
func (cfg MailgunEmailerConfig) EmailerID() string {
2015-09-22 04:09:29 +05:30
return MailgunEmailerType
2015-08-18 05:57:27 +05:30
}
func (cfg MailgunEmailerConfig) Emailer(fromAddr string) (Emailer, error) {
from := cfg.FromAddr
if from == "" {
from = fromAddr
}
if from == "" {
return nil, errors.New(`missing "from" field in email config`)
}
2015-08-18 05:57:27 +05:30
mg := mailgun.NewMailgun(cfg.Domain, cfg.PrivateAPIKey, cfg.PublicAPIKey)
return &mailgunEmailer{
mg: mg,
from: from,
2015-08-18 05:57:27 +05:30
}, nil
}
// mailgunEmailerConfig exists to avoid recusion.
type mailgunEmailerConfig MailgunEmailerConfig
func (cfg *MailgunEmailerConfig) UnmarshalJSON(data []byte) error {
mgtmp := mailgunEmailerConfig{}
err := json.Unmarshal(data, &mgtmp)
if err != nil {
return err
}
if mgtmp.PrivateAPIKey == "" {
return errors.New("must have a privateAPIKey set")
}
if mgtmp.PublicAPIKey == "" {
return errors.New("must have a publicAPIKey set")
}
if mgtmp.Domain == "" {
return errors.New("must have a domain set")
}
*cfg = MailgunEmailerConfig(mgtmp)
return nil
}
type mailgunEmailer struct {
mg mailgun.Mailgun
from string
2015-08-18 05:57:27 +05:30
}
func (m *mailgunEmailer) SendMail(subject, text, html string, to ...string) error {
msg := m.mg.NewMessage(m.from, subject, text, to...)
2015-08-18 05:57:27 +05:30
if html != "" {
msg.SetHtml(html)
}
mes, id, err := m.mg.Send(msg)
if err != nil {
counterEmailSendErr.Add(1)
return err
}
log.Infof("SendMail: msgID: %v: %q", id, mes)
return nil
}