-
Notifications
You must be signed in to change notification settings - Fork 6
/
sendgrid.go
47 lines (38 loc) · 1.14 KB
/
sendgrid.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
package mailer
import (
"github.com/kelseyhightower/envconfig"
"github.com/pkg/errors"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
)
type SendGrid struct {
fromname string
fromaddr string
client *sendgrid.Client
}
type Config struct {
SendgridFromName string `envconfig:"SENDGRID_FROM_NAME" required:"true"`
SendgridFromAddr string `envconfig:"SENDGRID_FROM_ADDR" required:"true"`
SendgridAPIKey string `envconfig:"SENDGRID_API_KEY" required:"true"`
}
func NewSendGrid() (Mailer, error) {
var cfg Config
if err := envconfig.Process("", &cfg); err != nil {
return nil, errors.Wrap(err, "failed to load sendgrid configuration")
}
return &SendGrid{
cfg.SendgridFromName,
cfg.SendgridFromAddr,
sendgrid.NewSendClient(cfg.SendgridAPIKey),
}, nil
}
func (m *SendGrid) Mail(toname, toaddr, subj, rich, text string) error {
from := mail.NewEmail(m.fromname, m.fromaddr)
to := mail.NewEmail(toname, toaddr)
message := mail.NewSingleEmail(from, subj, to, text, rich)
_, err := m.client.Send(message)
if err != nil {
return errors.Wrap(err, "failed to send email via sendgrid")
}
return nil
}