-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathmailjet_client.go
289 lines (242 loc) · 7.29 KB
/
mailjet_client.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Package mailjet provides methods for interacting with the last version of the Mailjet API.
// The goal of this component is to simplify the usage of the MailJet API for GO developers.
//
// For more details, see the full API Documentation at http://dev.mailjet.com/
package mailjet
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/textproto"
"os"
"strings"
)
// NewMailjetClient returns a new MailjetClient using an public apikey
// and an secret apikey to be used when authenticating to API.
func NewMailjetClient(apiKeyPublic, apiKeyPrivate string, baseURL ...string) *Client {
httpClient := NewHTTPClient(apiKeyPublic, apiKeyPrivate)
smtpClient := NewSMTPClient(apiKeyPublic, apiKeyPrivate)
client := &Client{
httpClient: httpClient,
smtpClient: smtpClient,
apiBase: apiBase,
}
if len(baseURL) > 0 {
client.apiBase = baseURL[0]
}
return client
}
// NewClient function
func NewClient(httpCl HTTPClientInterface, smtpCl SMTPClientInterface, baseURL ...string) *Client {
client := &Client{
httpClient: httpCl,
smtpClient: smtpCl,
apiBase: apiBase,
}
if len(baseURL) > 0 {
client.apiBase = baseURL[0]
}
return client
}
// SetBaseURL sets the base URL
func (c *Client) SetBaseURL(baseURL string) {
c.apiBase = baseURL
}
// APIKeyPublic returns the public key.
func (c *Client) APIKeyPublic() string {
return c.httpClient.APIKeyPublic()
}
// APIKeyPrivate returns the secret key.
func (c *Client) APIKeyPrivate() string {
return c.httpClient.APIKeyPrivate()
}
// SetURL function to set the base url of the wrapper instance
func (c *Client) SetURL(baseURL string) {
c.Lock()
defer c.Unlock()
c.apiBase = baseURL
}
// Client returns the underlying http client
func (c *Client) Client() *http.Client {
return c.httpClient.Client()
}
// SetClient allows to customize http client.
func (c *Client) SetClient(client *http.Client) {
c.Lock()
defer c.Unlock()
c.httpClient.SetClient(client)
}
// Filter applies a filter with the defined key and value.
func Filter(key, value string) RequestOptions {
return func(req *http.Request) {
q := req.URL.Query()
q.Add(key, value)
req.URL.RawQuery = strings.Replace(q.Encode(), "%2B", "+", 1)
}
}
// WithContext sets the request context
func WithContext(ctx context.Context) RequestOptions {
return func(req *http.Request) {
*req = *(req.WithContext(ctx))
}
}
// SortOrder defines the order of the result.
type SortOrder int
// These are the two possible order.
const (
SortDesc = SortOrder(iota)
SortAsc
)
var debugOut io.Writer = os.Stderr
// SetDebugOutput sets the output destination for the debug.
func SetDebugOutput(w io.Writer) {
debugOut = w
log.SetOutput(w)
}
// Sort applies the Sort filter to the request.
func Sort(value string, order SortOrder) RequestOptions {
if order == SortDesc {
value += "+DESC"
}
return Filter("Sort", value)
}
// List issues a GET to list the specified resource
// and stores the result in the value pointed to by res.
// Filters can be add via functional options.
func (c *Client) List(resource string, resp interface{}, options ...RequestOptions) (count, total int, err error) {
url := buildURL(c.apiBase, &Request{Resource: resource})
req, err := createRequest("GET", url, nil, nil, options...)
if err != nil {
return count, total, err
}
c.Lock()
defer c.Unlock()
return c.httpClient.Send(req).Read(resp).Call()
}
// Get issues a GET to view a resource specifying an id
// and stores the result in the value pointed to by res.
// Filters can be add via functional options.
// Without an specified ID in MailjetRequest, it is the same as List.
func (c *Client) Get(mr *Request, resp interface{}, options ...RequestOptions) (err error) {
url := buildURL(c.apiBase, mr)
req, err := createRequest("GET", url, nil, nil, options...)
if err != nil {
return err
}
c.Lock()
defer c.Unlock()
_, _, err = c.httpClient.Send(req).Read(resp).Call()
return err
}
// Post issues a POST to create a new resource
// and stores the result in the value pointed to by res.
// Filters can be add via functional options.
func (c *Client) Post(fmr *FullRequest, resp interface{}, options ...RequestOptions) (err error) {
url := buildURL(c.apiBase, fmr.Info)
req, err := createRequest("POST", url, fmr.Payload, nil, options...)
if err != nil {
return err
}
headers := map[string]string{"Content-Type": "application/json"}
c.Lock()
defer c.Unlock()
_, _, err = c.httpClient.Send(req).With(headers).Read(resp).Call()
return err
}
// Put is used to update a resource.
// Fields to be updated must be specified by the string array onlyFields.
// If onlyFields is nil, all fields except these with the tag read_only, are updated.
// Filters can be add via functional options.
func (c *Client) Put(fmr *FullRequest, onlyFields []string, options ...RequestOptions) (err error) {
url := buildURL(c.apiBase, fmr.Info)
req, err := createRequest("PUT", url, fmr.Payload, onlyFields, options...)
if err != nil {
return err
}
headers := map[string]string{"Content-Type": "application/json"}
c.Lock()
defer c.Unlock()
_, _, err = c.httpClient.Send(req).With(headers).Call()
return err
}
// Delete is used to delete a resource.
func (c *Client) Delete(mr *Request) (err error) {
url := buildURL(c.apiBase, mr)
req, err := createRequest("DELETE", url, nil, nil)
if err != nil {
return err
}
c.Lock()
defer c.Unlock()
_, _, err = c.httpClient.Send(req).Call()
return err
}
// SendMail send mail via API.
func (c *Client) SendMail(data *InfoSendMail, options ...RequestOptions) (res *SentResult, err error) {
url := c.apiBase + "/send/message"
req, err := createRequest("POST", url, data, nil, options...)
if err != nil {
return res, err
}
headers := map[string]string{"Content-Type": "application/json"}
c.Lock()
defer c.Unlock()
_, _, err = c.httpClient.Send(req).With(headers).Read(&res).Call()
return res, err
}
// SendMailSMTP send mail via SMTP.
func (c *Client) SendMailSMTP(info *InfoSMTP) error {
return c.smtpClient.SendMail(
info.From,
info.Recipients,
buildMessage(info.Header, info.Content))
}
func buildMessage(header textproto.MIMEHeader, content []byte) []byte {
buff := bytes.NewBuffer(nil)
for key, values := range header {
buff.WriteString(fmt.Sprintf("%s: %s\r\n", key, strings.Join(values, ", ")))
}
buff.WriteString("\r\n")
buff.Write(content)
return buff.Bytes()
}
// SendMailV31 sends a mail to the send API v3.1
func (c *Client) SendMailV31(data *MessagesV31, options ...RequestOptions) (*ResultsV31, error) {
url := c.apiBase + ".1/send"
req, err := createRequest("POST", url, data, nil, options...)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(c.APIKeyPublic(), c.APIKeyPrivate())
r, err := c.httpClient.SendMailV31(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
decoder := json.NewDecoder(r.Body)
switch r.StatusCode {
case http.StatusOK:
var res ResultsV31
if err := decoder.Decode(&res); err != nil {
return nil, err
}
return &res, nil
case http.StatusBadRequest, http.StatusForbidden:
var apiFeedbackErr APIFeedbackErrorsV31
if err := decoder.Decode(&apiFeedbackErr); err != nil {
return nil, err
}
return nil, &apiFeedbackErr
default:
var errInfo ErrorInfoV31
if err := decoder.Decode(&errInfo); err != nil {
return nil, err
}
return nil, &errInfo
}
}