forked from keighl/mandrill
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmandrill.go
612 lines (520 loc) · 21.6 KB
/
mandrill.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// A small library for sending emails through the Mandrill API. Inspired by [https://github.com/mostafah/// mandrill](@mostafah's implementation).
//
// Regular Message
//
// https://mandrillapp.com/api/docs/messages.JSON.html#method=send
//
// client := ClientWithKey("y2cQvBBfdFoZNByVaKsJsA")
//
// message := &Message{}
// message.AddRecipient("[email protected]", "Bob Johnson", "to")
// message.FromEmail = "[email protected]"
// message.FromName = "Kyle Truscott"
// message.Subject = "You won the prize!"
// message.HTML = "<h1>You won!!</h1>"
// message.Text = "You won!!"
//
// responses, err := client.MessagesSend(message)
//
// Send Template
//
// https://mandrillapp.com/api/docs/messages.JSON.html#method=send-template
//
// http://help.mandrill.com/entries/21694286-How-do-I-add-dynamic-content-using-editable-regions-in-my-template-
//
// templateContent := map[string]string{"header": "Bob! You won the prize!"}
// responses, err := client.MessagesSendTemplate(message, "you-won", templateContent)
//
// Including Merge Tags
//
// http://help.mandrill.com/entries/21678522-How-do-I-use-merge-tags-to-add-dynamic-content-
//
// message.GlobalMergeVars := mandrill.ConvertMapToVariables(map[string]interface{}{"name": "Bob"})
// message.MergeVars := mandrill.ConvertMapToVariablesForRecipient("[email protected]", map[string]interface{}{"name": "Bob"})
//
// Integration Testing Keys
// You can pass special API keys to the client to mock success/err responses from `MessagesSend` or `MessagesSendTemplate`.
// // Sending messages will be successful, but without a real API request
// c := ClientWithKey("SANDBOX_SUCCESS")
// // Sending messages will error, but without a real API request
// c := ClientWithKey("SANDBOX_ERROR")
package mandrill
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
// EmailClient defines the methods for a Mandrill Client
type EmailClient interface {
Ping() (pong string, err error)
MessagesSend(message *Message) (responses []*MessagesResponse, err error)
MessagesSendTemplate(message *Message, templateName string, contents interface{}) (
responses []*MessagesResponse, err error)
SubaccountInfo(subaccountID string) (response *Subaccount, err error)
AddSubaccount(subaccount *Subaccount) (response *Subaccount, err error)
DeleteSubaccount(subaccountID string) (response *Subaccount, err error)
UpdateSubaccount(subaccount *Subaccount) (response *Subaccount, err error)
TemplateInfo(templateName string) (response *Template, err error)
AddTemplate(template *Template) (response *Template, err error)
DeleteTemplate(templateName string) (response *Template, err error)
UpdateTemplate(template *Template) (response *Template, err error)
}
// Client manages requests to the Mandrill API
type Client struct {
// mandrill API key
Key string
// Mandrill API base. e.g. "https://mandrillapp.com/api/1.0/"
BaseURL string
// Requests are transported through this client
HTTPClient *http.Client
}
// Message represents the message payload sent to the API
type Message struct {
// the full HTML content to be sent
HTML string `json:"html,omitempty"`
// optional full text content to be sent
Text string `json:"text,omitempty"`
// the message subject
Subject string `json:"subject,omitempty"`
// the sender email address.
FromEmail string `json:"from_email,omitempty"`
// optional from name to be used
FromName string `json:"from_name,omitempty"`
// an array of recipient information.
To []*To `json:"to"`
// optional extra headers to add to the message (most headers are allowed)
Headers map[string]string `json:"headers,omitempty"`
// whether or not this message is important, and should be delivered ahead of non-important messages
Important bool `json:"important,omitempty"`
// whether or not to turn on open tracking for the message
TrackOpens bool `json:"track_opens,omitempty"`
// whether or not to turn on click tracking for the message
TrackClicks bool `json:"track_clicks,omitempty"`
// whether or not to automatically generate a text part for messages that are not given text
AutoText bool `json:"auto_text,omitempty"`
// whether or not to automatically generate an HTML part for messages that are not given HTML
AutoHTML bool `json:"auto_html,omitempty"`
// whether or not to automatically inline all CSS styles provided in the message HTML - only for HTML documents less than 256KB in size
InlineCSS bool `json:"inline_css,omitempty"`
// whether or not to strip the query string from URLs when aggregating tracked URL data
URLStripQS bool `json:"url_strip_qs,omitempty"`
// whether or not to expose all recipients in to "To" header for each email
PreserveRecipients bool `json:"preserve_recipients,omitempty"`
// set to false to remove content logging for sensitive emails
ViewContentLink bool `json:"view_content_link,omitempty"`
// an optional address to receive an exact copy of each recipient's email
BCCAddress string `json:"bcc_address,omitempty"`
// a custom domain to use for tracking opens and clicks instead of mandrillapp.com
TrackingDomain string `json:"tracking_domain,omitempty"`
// a custom domain to use for SPF/DKIM signing instead of mandrill (for "via" or "on behalf of" in email clients)
SigningDomain string `json:"signing_domain,omitempty"`
// a custom domain to use for the messages's return-path
ReturnPathDomain string `json:"return_path_domain,omitempty"`
// whether to evaluate merge tags in the message. Will automatically be set to true if either merge_vars or global_merge_vars are provided.
Merge bool `json:"merge,omitempty"`
// the merge tag language to use when evaluating merge tags, either mailchimp or handlebars
MergeLanguage string `json:"merge_language,omitempty"`
// global merge variables to use for all recipients. You can override these per recipient.
GlobalMergeVars []*Variable `json:"global_merge_vars,omitempty"`
// per-recipient merge variables, which override global merge variables with the same name.
MergeVars []*RcptMergeVars `json:"merge_vars,omitempty"`
// an array of string to tag the message with. Stats are accumulated using tags, though we only store the first 100 we see, so this should not be unique or change frequently. Tags should be 50 characters or less. Any tags starting with an underscore are reserved for internal use and will cause errors.
Tags []string `json:"tags,omitempty"`
// the unique id of a subaccount for this message - must already exist or will fail with an error
Subaccount string `json:"subaccount,omitempty"`
// an array of strings indicating for which any matching URLs will automatically have Google Analytics parameters appended to their query string automatically.
GoogleAnalyticsDomains []string `json:"google_analytics_domains,omitempty"`
// optional string indicating the value to set for the utm_campaign tracking parameter. If this isn't provided the email's from address will be used instead.
GoogleAnalyticsCampaign string `json:"google_analytics_campaign,omitempty"`
// metadata an associative array of user metadata. Mandrill will store this metadata and make it available for retrieval. In addition, you can select up to 10 metadata fields to index and make searchable using the Mandrill search api.
Metadata map[string]string `json:"metadata,omitempty"`
// Per-recipient metadata that will override the global values specified in the metadata parameter.
RecipientMetadata []*RcptMetadata `json:"recipient_metadata,omitempty"`
// Per-recipient metadata that will override the global values specified in the metadata parameter.
Attachments []*Attachment `json:"attachments,omitempty"`
// an array of embedded images to add to the message
Images []*Attachment `json:"images,omitempty"`
// enable a background sending mode that is optimized for bulk sending. In async mode, messages/send will immediately return a status of "queued" for every recipient. To handle rejections when sending in async mode, set up a webhook for the 'reject' event. Defaults to false for messages with no more than 10 recipients; messages with more than 10 recipients are always sent asynchronously, regardless of the value of async.
Async bool `json:"-"`
// the name of the dedicated ip pool that should be used to send the message. If you do not have any dedicated IPs, this parameter has no effect. If you specify a pool that does not exist, your default pool will be used instead.
IPPool string `json:"-"`
// when this message should be sent as a UTC timestamp in YYYY-MM-DD HH:MM:SS format. If you specify a time in the past, the message will be sent immediately. An additional fee applies for scheduled email, and this feature is only available to accounts with a positive balance.
SendAt string `json:"-"`
}
// Template represents the template payload sent to the API
type Template struct {
// api key
Key string `json:"key"`
// the template name, unique
Name string `json:"name"`
// the immutable unique code name of the template
Slug string `json:"slug,omitempty"`
// the message subject
Subject string `json:"subject,omitempty"`
// the sender email address.
FromEmail string `json:"from_email,omitempty"`
// optional from name to be used
FromName string `json:"from_name,omitempty"`
// the full HTML content to be sent
HTML string `json:"code,omitempty"`
// optional full text content to be sent
Text string `json:"text,omitempty"`
// an optional array of up to 10 labels to use for filtering templates
Labels []string `json:"labels,omitempty"`
}
// Subaccount struct to send & receive responses via Subaccount API
type Subaccount struct {
// api key
Key string `json:"key"`
// subaccount id
Id string `json:"id"`
Name string `json:"name,omitempty"`
Notes string `json:"notes,omitempty"`
// custom quota (hourly)
Quota int `json:"custom_quota,omitempty"`
// response only fields
Reputation int `json:"reputation,omitempty"`
Status string `json:"status,omitempty"`
Sent_hourly int `json:"sent_hourly,omitempty"`
Sent_weekly int `json:"sent_weekly,omitempty"`
Sent_monthly int `json:"sent_monthly,omitempty"`
Sent_total int `json:"sent_total,omitempty"`
}
// To is a single recipient's information.
type To struct {
// the email address of the recipient
Email string `json:"email"`
// the optional display name to use for the recipient
Name string `json:"name,omitempty"`
// the header type to use for the recipient, defaults to "to" if not provided
// oneof(to, cc, bcc)
Type RecipientType `json:"type,omitempty"`
}
// Variable is key/value data used throughout the Mandrill API
type Variable struct {
Name string `json:"name"`
Content interface{} `json:"content"`
}
// RcptMergeVars holds per-recipient merge variables
type RcptMergeVars struct {
// the email address of the recipient that the merge variables should apply to
Rcpt string `json:"rcpt"`
// the recipient's merge variables
Vars []*Variable `json:"vars"`
}
// RcptMetadata holds metadata for a single recipient
type RcptMetadata struct {
// the email address of the recipient that the metadata is associated with
Rcpt string `json:"rcpt"`
// an associated array containing the recipient's unique metadata. If a key exists in both the per-recipient metadata and the global metadata, the per-recipient metadata will be used.
Values map[string]interface{} `json:"values"`
}
// Attachment represents a single supported attachment
type Attachment struct {
// the MIME type of the attachment
Type string `json:"type"`
// the file name of the attachment
Name string `json:"name"`
// the content of the attachment as a base64-encoded string
Content string `json:"content"`
}
// MessagesResponse holds details of the message status
type MessagesResponse struct {
// the email address of the recipient
Email string `json:"email"`
// the sending status of the recipient - either "sent", "queued", "scheduled", "rejected", or "invalid"
Status string `json:"status"`
// the reason for the rejection if the recipient status is "rejected" - one of "hard-bounce", "soft-bounce", "spam", "unsub", "custom", "invalid-sender", "invalid", "test-mode-limit", or "rule"
RejectionReason string `json:"reject_reason"`
// the message's unique id
Id string `json:"_id"`
}
// Error reprents an error from the Mandrill API
// * Invalid_Key -The provided API key is not a valid Mandrill API key\r
// * PaymentRequired -The requested feature requires payment.\r
// * Unknown_Subaccount - The provided subaccount id does not exist.\r
// * ValidationError - The parameters passed to the API call are invalid or not provided when required\r
// * GeneralError - An unexpected error occurred processing the request. Mandrill developers will be notified.\r
type Error struct {
Status string `json:"status"`
Code int `json:"code"`
Name string `json:"name"`
Message string `json:"message"`
}
// Error returns err.Message
func (err Error) Error() string {
return err.Message
}
// ClientWithKey returns a mandrill.Client pointer armed with the supplied Mandrill API key
// For integration testing, you can supply `SANDBOX_SUCCESS` or `SANDBOX_ERROR` as the API key.
func ClientWithKey(key string) *Client {
return &Client{
Key: key,
HTTPClient: &http.Client{},
BaseURL: "https://mandrillapp.com/api/1.0/",
}
}
// Ping checks that the Client is able to communicate with Mandrill's remote services.
func (c *Client) Ping() (pong string, err error) {
var data struct {
Key string `json:"key"`
}
data.Key = c.Key
body, err := c.sendAPIRequest(data, "users/ping.json")
if err != nil {
return pong, err
}
err = json.Unmarshal(body, &pong)
return pong, err
}
// MessagesSend sends a message via an API client
func (c *Client) MessagesSend(message *Message) (responses []*MessagesResponse, err error) {
var data struct {
Key string `json:"key"`
Message *Message `json:"message,omitempty"`
// Remapped from Message.Async
Async bool `json:"async,omitempty"`
// Remapped from Message.IPPool
IPPool string `json:"ip_pool,omitempty"`
// Remapped from Message.SendAt
SendAt string `json:"send_at,omitempty"`
}
data.Key = c.Key
data.Message = message
data.Async = message.Async
data.IPPool = message.IPPool
data.SendAt = message.SendAt
return c.sendMessagePayload(data, "messages/send.json")
}
// MessagesSendTemplate sends a message using a Mandrill template
func (c *Client) MessagesSendTemplate(message *Message, templateName string, contents interface{}) (responses []*MessagesResponse, err error) {
var data struct {
Key string `json:"key"`
TemplateName string `json:"template_name,omitempty"`
TemplateContent []*Variable `json:"template_content"`
Message *Message `json:"message,omitempty"`
// Remapped from Message.Async
Async bool `json:"async,omitempty"`
// Remapped from Message.IPPool
IPPool string `json:"ip_pool,omitempty"`
// Remapped from Message.SendAt
SendAt string `json:"send_at,omitempty"`
}
data.Key = c.Key
data.TemplateName = templateName
data.TemplateContent = ConvertMapToVariables(contents)
data.Message = message
data.Async = message.Async
data.IPPool = message.IPPool
data.SendAt = message.SendAt
return c.sendMessagePayload(data, "messages/send-template.json")
}
// AddTemplate adds a new template
func (c *Client) AddTemplate(template *Template) (response *Template, err error) {
template.Key = c.Key
body, err := c.sendAPIRequest(template, "templates/add.json")
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &response)
return response, err
}
// UpdateTemplate updates a template
func (c *Client) UpdateTemplate(template *Template) (response *Template, err error) {
template.Key = c.Key
body, err := c.sendAPIRequest(template, "templates/update.json")
if err != nil {
return response, err
}
err = json.Unmarshal(body, &response)
return response, err
}
// DeleteTemplate removes a template
func (c *Client) DeleteTemplate(templateName string) (response *Template, err error) {
var data struct {
Key string `json:"key"`
Name string `json:"name"`
}
data.Key = c.Key
data.Name = templateName
body, err := c.sendAPIRequest(data, "templates/delete.json")
if err != nil {
return response, err
}
err = json.Unmarshal(body, &response)
return response, err
}
// TemplateInfo gets a template
func (c *Client) TemplateInfo(templateName string) (response *Template, err error) {
var data struct {
Key string `json:"key"`
Name string `json:"name"`
}
data.Key = c.Key
data.Name = templateName
body, err := c.sendAPIRequest(data, "templates/info.json")
if err != nil {
return response, err
}
err = json.Unmarshal(body, &response)
return response, err
}
// AddSubaccount adds a new subaccount
func (c *Client) AddSubaccount(subaccount *Subaccount) (response *Subaccount, err error) {
subaccount.Key = c.Key
body, err := c.sendAPIRequest(subaccount, "subaccounts/add.json")
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &response)
return response, err
}
// UpdateSubaccount updates a subaccount
func (c *Client) UpdateSubaccount(subaccount *Subaccount) (response *Subaccount, err error) {
subaccount.Key = c.Key
body, err := c.sendAPIRequest(subaccount, "subaccounts/update.json")
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &response)
return response, err
}
// DeleteSubaccount removes a subaccount
func (c *Client) DeleteSubaccount(subaccountID string) (response *Subaccount, err error) {
var data struct {
Key string `json:"key"`
ID string `json:"id"`
}
data.Key = c.Key
data.ID = subaccountID
body, err := c.sendAPIRequest(data, "subaccounts/delete.json")
if err != nil {
return response, err
}
err = json.Unmarshal(body, &response)
return response, err
}
// SubaccountInfo gets subaccount info
func (c *Client) SubaccountInfo(subaccountID string) (response *Subaccount, err error) {
var data struct {
Key string `json:"key"`
ID string `json:"id"`
}
data.Key = c.Key
data.ID = subaccountID
body, err := c.sendAPIRequest(data, "subaccounts/info.json")
if err != nil {
return response, err
}
err = json.Unmarshal(body, &response)
return response, err
}
// RecipientType represents the type of recipient (to, cc, bcc)
type RecipientType string
const (
// TO indicates that this is a primary recipient
TO RecipientType = "to"
// CC indicates that this is a secondary recipient
CC RecipientType = "cc"
// BCC indicates that this is a secret recipient
BCC RecipientType = "bcc"
)
// AddRecipient appends a recipient to the message
// easier than message.To = []*To{&To{email, name}}
func (m *Message) AddRecipient(email string, name string, sendType RecipientType) {
to := &To{email, name, sendType}
m.To = append(m.To, to)
}
// AddTo adds a recipient with type "to"
func (m *Message) AddTo(email, name string) {
m.AddRecipient(email, name, TO)
}
// AddCC adds a recipient with type "cc"
func (m *Message) AddCC(email, name string) {
m.AddRecipient(email, name, CC)
}
// AddBCC adds a recipient with type "bcc"
func (m *Message) AddBCC(email, name string) {
m.AddRecipient(email, name, BCC)
}
// AddVariable adds a map of values to the message
func (m *Message) AddVariable(email, key string, value interface{}) {
values := make(map[string]interface{})
values[key] = value
m.AddVariables(email, values)
}
// AddVariables adds a map of values to the message
func (m *Message) AddVariables(email string, values map[string]interface{}) {
recipientMergeVars := MapToRecipientVars(email, values)
m.MergeVars = append(m.MergeVars, recipientMergeVars)
}
func (c *Client) sendMessagePayload(data interface{}, path string) (responses []*MessagesResponse, err error) {
if c.Key == "SANDBOX_SUCCESS" {
return []*MessagesResponse{}, nil
}
if c.Key == "SANDBOX_ERROR" {
return nil, errors.New("SANDBOX_ERROR")
}
body, err := c.sendAPIRequest(data, path)
if err != nil {
return responses, err
}
responses = make([]*MessagesResponse, 0)
err = json.Unmarshal(body, &responses)
return responses, err
}
func (c *Client) sendAPIRequest(data interface{}, path string) (body []byte, err error) {
payload, _ := json.Marshal(data)
resp, err := c.HTTPClient.Post(c.BaseURL+path, "application/json", bytes.NewReader(payload))
if err != nil {
return body, err
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return body, err
}
if resp.StatusCode >= 400 {
resError := &Error{}
json.Unmarshal(body, resError)
return body, resError
}
return body, err
}
// ConvertMapToVariables converts a regular string/string map into the Variable struct
// e.g. `vars := ConvertMapToVariables(map[string]interface{}{"bob": "cheese"})`
func ConvertMapToVariables(i interface{}) []*Variable {
imap := map[string]interface{}{}
switch i.(type) {
// Handle older API for passing just map[string]string
case map[string]string:
for k, v := range i.(map[string]string) {
imap[k] = v
}
case map[string]interface{}:
imap, _ = i.(map[string]interface{})
default:
return []*Variable{}
}
variables := make([]*Variable, 0, len(imap))
for k, v := range imap {
variables = append(variables, &Variable{k, v})
}
return variables
}
// MapToVars converts a regular string/string map into the Variable struct
// Alias of `ConvertMapToVariables`
func MapToVars(m interface{}) []*Variable {
return ConvertMapToVariables(m)
}
// ConvertMapToVariablesForRecipient converts a regular string/string map into the RcptMergeVars struct
func ConvertMapToVariablesForRecipient(email string, m interface{}) *RcptMergeVars {
return &RcptMergeVars{Rcpt: email, Vars: ConvertMapToVariables(m)}
}
// MapToRecipientVars converts a regular string/string map into the RcptMergeVars struct
// Alias of `ConvertMapToVariablesForRecipient`
func MapToRecipientVars(email string, m interface{}) *RcptMergeVars {
return ConvertMapToVariablesForRecipient(email, m)
}