-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmailgun_manager.go
78 lines (62 loc) · 1.7 KB
/
mailgun_manager.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
package email
import (
"context"
"os"
"time"
"github.com/mailgun/mailgun-go/v4"
"github.com/adwitiyaio/arka/logger"
"github.com/adwitiyaio/arka/secrets"
)
const domainKey = "MAILGUN_DOMAIN"
const apiKey = "MAILGUN_API_KEY"
type mailgunManager struct {
sm secrets.Manager
mg *mailgun.MailgunImpl
}
func (m *mailgunManager) initialize() {
domain := m.sm.GetValueForKey(domainKey)
apiKey := m.sm.GetValueForKey(apiKey)
if domain == "" || apiKey == "" {
logger.Log.Panic().Msg("failed to initialize mailgun")
}
m.mg = mailgun.NewMailgun(domain, apiKey)
}
func (m *mailgunManager) SendEmail(options Options) (interface{}, error) {
message := m.mg.NewMessage(options.Sender, options.Subject, options.Text)
for _, to := range options.To {
err := message.AddRecipient(to)
if err != nil {
logger.Log.Error().Str("recipient", to).Err(err).Stack().Msg("failed to add recipient")
}
}
for _, cc := range options.Cc {
message.AddCC(cc)
}
for _, bcc := range options.Bcc {
message.AddBCC(bcc)
}
message.SetHtml(options.Html)
if len(options.Attachments) > 0 {
for _, attachment := range options.Attachments {
message.AddAttachment(attachment)
}
}
message.SetTracking(true)
message.SetTrackingClicks(true)
message.SetTrackingOpens(true)
return m.dispatch(message, options)
}
func (m *mailgunManager) dispatch(message *mailgun.Message, options Options) (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
var resp string
var err error
if os.Getenv("CI") != "true" {
resp, _, err = m.mg.Send(ctx, message)
}
if err != nil {
logger.Log.Error().Err(err).Stack().Msg("failed to send email")
return nil, err
}
return resp, nil
}