forked from getfider/fider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailgun.go
126 lines (107 loc) · 3.52 KB
/
mailgun.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package mailgun
import (
"encoding/json"
"fmt"
"net/url"
"strings"
"github.com/getfider/fider/app/pkg/email"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/web/http"
)
var baseURL = "https://api.mailgun.net/v3/%s/messages"
//Sender is used to send emails
type Sender struct {
logger log.Logger
client http.Client
domain string
apiKey string
}
//NewSender creates a new mailgun email sender
func NewSender(logger log.Logger, client http.Client, domain, apiKey string) *Sender {
return &Sender{logger, client, domain, apiKey}
}
//Send an email
func (s *Sender) Send(ctx email.Context, templateName string, params email.Params, from string, to email.Recipient) error {
return s.BatchSend(ctx, templateName, params, from, []email.Recipient{to})
}
// BatchSend an email to multiple recipients
func (s *Sender) BatchSend(ctx email.Context, templateName string, params email.Params, from string, to []email.Recipient) error {
if len(to) == 0 {
return nil
}
isBatch := len(to) > 1
var message *email.Message
if isBatch {
// Replace recipient specific Go templates variables with Mailgun template variables
for k := range to[0].Params {
params[k] = fmt.Sprintf("%%recipient.%s%%", k)
}
message = email.RenderMessage(ctx, templateName, params)
} else {
message = email.RenderMessage(ctx, templateName, params.Merge(to[0].Params))
}
form := url.Values{}
form.Add("from", email.NewRecipient(from, email.NoReply, email.Params{}).String())
form.Add("h:Reply-To", email.NoReply)
form.Add("subject", message.Subject)
form.Add("html", message.Body)
form.Add("o:tag", fmt.Sprintf("template:%s", templateName))
if ctx.Tenant() != nil && !env.IsSingleHostMode() {
form.Add("o:tag", fmt.Sprintf("tenant:%s", ctx.Tenant().Subdomain))
}
// Set Mailgun's var based on each recipient's variables
recipientVariables := make(map[string]email.Params, 0)
for _, r := range to {
if r.Address != "" {
if email.CanSendTo(r.Address) {
form.Add("to", r.String())
recipientVariables[r.Address] = r.Params
} else {
s.logger.Warnf("Skipping email to '@{Name} <@{Address}>'.", log.Props{
"Name": r.Name,
"Address": r.Address,
})
}
}
}
// If we skipped all recipients, just return
if len(recipientVariables) == 0 {
return nil
}
if isBatch {
json, err := json.Marshal(recipientVariables)
if err != nil {
return errors.Wrap(err, "failed to marshal recipient variables")
}
form.Add("recipient-variables", string(json))
}
if isBatch {
s.logger.Debugf("Sending email to @{CountRecipients} recipients with template @{TemplateName}.", log.Props{
"CountRecipients": len(recipientVariables),
"TemplateName": templateName,
})
} else {
s.logger.Debugf("Sending email to @{Address} with template @{TemplateName}.", log.Props{
"Address": to[0].Address,
"TemplateName": templateName,
})
}
url := fmt.Sprintf(baseURL, s.domain)
request, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
if err != nil {
return errors.Wrap(err, "failed to create POST request")
}
request.SetBasicAuth("api", s.apiKey)
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := s.client.Do(request)
if err != nil {
return errors.Wrap(err, "failed to send email with template %s", templateName)
}
defer resp.Body.Close()
s.logger.Debugf("Email sent with response code @{StatusCode}.", log.Props{
"StatusCode": resp.StatusCode,
})
return nil
}