-
Notifications
You must be signed in to change notification settings - Fork 3
/
sendgridexporter.go
97 lines (74 loc) · 1.82 KB
/
sendgridexporter.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
92
93
94
95
96
97
// +build segment
package eventexporter
import sendgrid "github.com/sendgrid/sendgrid-go"
const (
DefaultFromName = "Koding"
DefaultFromAddress = "[email protected]"
)
type SendgridExporter struct {
Client *sendgrid.SGClient
}
func NewSendgridExporter(username, password string) *SendgridExporter {
return &SendgridExporter{
Client: sendgrid.NewSendGridClient(username, password),
}
}
func (s *SendgridExporter) Send(event *Event) error {
var err error
mail := sendgrid.NewMail()
if mail, err = setTo(mail, event); err != nil {
return err
}
if mail, err = setFrom(mail, event); err != nil {
return err
}
if mail, err = setBody(mail, event); err != nil {
return err
}
if mail, err = setSubject(mail, event); err != nil {
return err
}
return s.Client.Send(mail)
}
func (s *SendgridExporter) Close() error {
return nil
}
func setTo(mail *sendgrid.SGMail, event *Event) (*sendgrid.SGMail, error) {
err := mail.AddTo(event.User.Email)
if err != nil {
return nil, err
}
return mail, nil
}
func setFrom(mail *sendgrid.SGMail, event *Event) (*sendgrid.SGMail, error) {
from, ok := event.Properties["from"]
if !ok {
from = DefaultFromAddress
}
if err := mail.SetFrom(from.(string)); err != nil {
return nil, err
}
fromName, ok := event.Properties["fromName"]
if !ok {
fromName = DefaultFromName
}
mail.SetFromName(fromName.(string))
return mail, nil
}
func setBody(mail *sendgrid.SGMail, event *Event) (*sendgrid.SGMail, error) {
if event.Body == nil {
return nil, ErrSendgridBodyEmpty
}
bodyType := event.Body.Type
switch bodyType {
case HtmlBodyType:
mail.SetHTML(event.Body.Content)
case TextBodyType:
mail.SetText(event.Body.Content)
}
return mail, nil
}
func setSubject(mail *sendgrid.SGMail, event *Event) (*sendgrid.SGMail, error) {
mail.SetSubject(event.Name)
return mail, nil
}