-
Notifications
You must be signed in to change notification settings - Fork 143
/
messages.go
926 lines (800 loc) · 28.5 KB
/
messages.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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
package mailgun
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"time"
)
// MaxNumberOfRecipients represents the largest batch of recipients that Mailgun can support in a single API call.
// This figure includes To:, Cc:, Bcc:, etc. recipients.
const MaxNumberOfRecipients = 1000
// MaxNumberOfTags represents the maximum number of tags that can be added for a message
const MaxNumberOfTags = 3
// Message structures contain both the message text and the envelop for an e-mail message.
type Message struct {
to []string
tags []string
campaigns []string
dkim bool
deliveryTime time.Time
stoPeriod string
attachments []string
readerAttachments []ReaderAttachment
inlines []string
readerInlines []ReaderAttachment
bufferAttachments []BufferAttachment
nativeSend bool
testMode bool
tracking bool
trackingClicks string
trackingOpens bool
headers map[string]string
variables map[string]string
templateVariables map[string]interface{}
recipientVariables map[string]map[string]interface{}
domain string
templateVersionTag string
templateRenderText bool
dkimSet bool
trackingSet bool
trackingClicksSet bool
trackingOpensSet bool
requireTLS bool
skipVerification bool
specific features
mg Mailgun
}
type ReaderAttachment struct {
Filename string
ReadCloser io.ReadCloser
}
type BufferAttachment struct {
Filename string
Buffer []byte
}
// StoredMessage structures contain the (parsed) message content for an email
// sent to a Mailgun account.
//
// The MessageHeaders field is special, in that it's formatted as a slice of pairs.
// Each pair consists of a name [0] and value [1]. Array notation is used instead of a map
// because that's how it's sent over the wire, and it's how encoding/json expects this field
// to be.
type StoredMessage struct {
Recipients string `json:"recipients"`
Sender string `json:"sender"`
From string `json:"from"`
Subject string `json:"subject"`
BodyPlain string `json:"body-plain"`
StrippedText string `json:"stripped-text"`
StrippedSignature string `json:"stripped-signature"`
BodyHtml string `json:"body-html"`
StrippedHtml string `json:"stripped-html"`
Attachments []StoredAttachment `json:"attachments"`
MessageUrl string `json:"message-url"`
ContentIDMap map[string]struct {
Url string `json:"url"`
ContentType string `json:"content-type"`
Name string `json:"name"`
Size int64 `json:"size"`
} `json:"content-id-map"`
MessageHeaders [][]string `json:"message-headers"`
}
// StoredAttachment structures contain information on an attachment associated with a stored message.
type StoredAttachment struct {
Size int `json:"size"`
Url string `json:"url"`
Name string `json:"name"`
ContentType string `json:"content-type"`
}
type StoredMessageRaw struct {
Recipients string `json:"recipients"`
Sender string `json:"sender"`
From string `json:"from"`
Subject string `json:"subject"`
BodyMime string `json:"body-mime"`
}
// plainMessage contains fields relevant to plain API-synthesized messages.
// You're expected to use various setters to set most of these attributes,
// although from, subject, and text are set when the message is created with
// NewMessage.
type plainMessage struct {
from string
cc []string
bcc []string
subject string
text string
html string
ampHtml string
template string
}
// mimeMessage contains fields relevant to pre-packaged MIME messages.
type mimeMessage struct {
body io.ReadCloser
}
type sendMessageResponse struct {
Message string `json:"message"`
Id string `json:"id"`
}
// TrackingOptions contains fields relevant to trackings.
type TrackingOptions struct {
Tracking bool
TrackingClicks string
TrackingOpens bool
}
// features abstracts the common characteristics between regular and MIME messages.
// addCC, addBCC, recipientCount, setHtml and setAMPHtml are invoked via the package-global AddCC, AddBCC,
// RecipientCount, SetHtml and SetAMPHtml calls, as these functions are ignored for MIME messages.
// Send() invokes addValues to add message-type-specific MIME headers for the API call
// to Mailgun. isValid yeilds true if and only if the message is valid enough for sending
// through the API. Finally, endpoint() tells Send() which endpoint to use to submit the API call.
type features interface {
addCC(string)
addBCC(string)
setHtml(string)
setAMPHtml(string)
addValues(*formDataPayload)
isValid() bool
endpoint() string
recipientCount() int
setTemplate(string)
}
// NewMessage returns a new e-mail message with the simplest envelop needed to send.
//
// Unlike the global function,
// this method supports arbitrary-sized recipient lists by
// automatically sending mail in batches of up to MaxNumberOfRecipients.
//
// To support batch sending, you don't want to provide a fixed To: header at this point.
// Pass nil as the to parameter to skip adding the To: header at this stage.
// You can do this explicitly, or implicitly, as follows:
//
// // Note absence of To parameter(s)!
// m := mg.NewMessage("[email protected]", "Help save our planet", "Hello world!")
//
// Note that you'll need to invoke the AddRecipientAndVariables or AddRecipient method
// before sending, though.
func (mg *MailgunImpl) NewMessage(from, subject, text string, to ...string) *Message {
return &Message{
specific: &plainMessage{
from: from,
subject: subject,
text: text,
},
to: to,
mg: mg,
}
}
// NewMIMEMessage creates a new MIME message. These messages are largely canned;
// you do not need to invoke setters to set message-related headers.
// However, you do still need to call setters for Mailgun-specific settings.
//
// Unlike the global function,
// this method supports arbitrary-sized recipient lists by
// automatically sending mail in batches of up to MaxNumberOfRecipients.
//
// To support batch sending, you don't want to provide a fixed To: header at this point.
// Pass nil as the to parameter to skip adding the To: header at this stage.
// You can do this explicitly, or implicitly, as follows:
//
// // Note absence of To parameter(s)!
// m := mg.NewMessage("[email protected]", "Help save our planet", "Hello world!")
//
// Note that you'll need to invoke the AddRecipientAndVariables or AddRecipient method
// before sending, though.
func (mg *MailgunImpl) NewMIMEMessage(body io.ReadCloser, to ...string) *Message {
return &Message{
specific: &mimeMessage{
body: body,
},
to: to,
mg: mg,
}
}
// AddReaderAttachment arranges to send a file along with the e-mail message.
// File contents are read from a io.ReadCloser.
// The filename parameter is the resulting filename of the attachment.
// The readCloser parameter is the io.ReadCloser which reads the actual bytes to be used
// as the contents of the attached file.
func (m *Message) AddReaderAttachment(filename string, readCloser io.ReadCloser) {
ra := ReaderAttachment{Filename: filename, ReadCloser: readCloser}
m.readerAttachments = append(m.readerAttachments, ra)
}
// AddBufferAttachment arranges to send a file along with the e-mail message.
// File contents are read from the []byte array provided
// The filename parameter is the resulting filename of the attachment.
// The buffer parameter is the []byte array which contains the actual bytes to be used
// as the contents of the attached file.
func (m *Message) AddBufferAttachment(filename string, buffer []byte) {
ba := BufferAttachment{Filename: filename, Buffer: buffer}
m.bufferAttachments = append(m.bufferAttachments, ba)
}
// AddAttachment arranges to send a file from the filesystem along with the e-mail message.
// The attachment parameter is a filename, which must refer to a file which actually resides
// in the local filesystem.
func (m *Message) AddAttachment(attachment string) {
m.attachments = append(m.attachments, attachment)
}
// AddReaderInline arranges to send a file along with the e-mail message.
// File contents are read from a io.ReadCloser.
// The filename parameter is the resulting filename of the attachment.
// The readCloser parameter is the io.ReadCloser which reads the actual bytes to be used
// as the contents of the attached file.
func (m *Message) AddReaderInline(filename string, readCloser io.ReadCloser) {
ra := ReaderAttachment{Filename: filename, ReadCloser: readCloser}
m.readerInlines = append(m.readerInlines, ra)
}
// AddInline arranges to send a file along with the e-mail message, but does so
// in a way that its data remains "inline" with the rest of the message. This
// can be used to send image or font data along with an HTML-encoded message body.
// The attachment parameter is a filename, which must refer to a file which actually resides
// in the local filesystem.
func (m *Message) AddInline(inline string) {
m.inlines = append(m.inlines, inline)
}
// AddRecipient appends a receiver to the To: header of a message.
// It will return an error if the limit of recipients have been exceeded for this message
func (m *Message) AddRecipient(recipient string) error {
return m.AddRecipientAndVariables(recipient, nil)
}
// AddRecipientAndVariables appends a receiver to the To: header of a message,
// and as well attaches a set of variables relevant for this recipient.
// It will return an error if the limit of recipients have been exceeded for this message
func (m *Message) AddRecipientAndVariables(r string, vars map[string]interface{}) error {
if m.RecipientCount() >= MaxNumberOfRecipients {
return fmt.Errorf("recipient limit exceeded (max %d)", MaxNumberOfRecipients)
}
m.to = append(m.to, r)
if vars != nil {
if m.recipientVariables == nil {
m.recipientVariables = make(map[string]map[string]interface{})
}
m.recipientVariables[r] = vars
}
return nil
}
// RecipientCount returns the total number of recipients for the message.
// This includes To:, Cc:, and Bcc: fields.
//
// NOTE: At present, this method is reliable only for non-MIME messages, as the
// Bcc: and Cc: fields are easily accessible.
// For MIME messages, only the To: field is considered.
// A fix for this issue is planned for a future release.
// For now, MIME messages are always assumed to have 10 recipients between Cc: and Bcc: fields.
// If your MIME messages have more than 10 non-To: field recipients,
// you may find that some recipients will not receive your e-mail.
// It's perfectly OK, of course, for a MIME message to not have any Cc: or Bcc: recipients.
func (m *Message) RecipientCount() int {
return len(m.to) + m.specific.recipientCount()
}
func (pm *plainMessage) recipientCount() int {
return len(pm.bcc) + len(pm.cc)
}
func (mm *mimeMessage) recipientCount() int {
return 10
}
func (m *Message) send(ctx context.Context) (string, string, error) {
return m.mg.Send(ctx, m)
}
// SetReplyTo sets the receiver who should receive replies
func (m *Message) SetReplyTo(recipient string) {
m.AddHeader("Reply-To", recipient)
}
// AddCC appends a receiver to the carbon-copy header of a message.
func (m *Message) AddCC(recipient string) {
m.specific.addCC(recipient)
}
func (pm *plainMessage) addCC(r string) {
pm.cc = append(pm.cc, r)
}
func (mm *mimeMessage) addCC(_ string) {}
// AddBCC appends a receiver to the blind-carbon-copy header of a message.
func (m *Message) AddBCC(recipient string) {
m.specific.addBCC(recipient)
}
func (pm *plainMessage) addBCC(r string) {
pm.bcc = append(pm.bcc, r)
}
func (mm *mimeMessage) addBCC(_ string) {}
// SetHtml is a helper. If you're sending a message that isn't already MIME encoded, SetHtml() will arrange to bundle
// an HTML representation of your message in addition to your plain-text body.
func (m *Message) SetHtml(html string) {
m.specific.setHtml(html)
}
func (pm *plainMessage) setHtml(h string) {
pm.html = h
}
func (mm *mimeMessage) setHtml(_ string) {}
// SetAMP is a helper. If you're sending a message that isn't already MIME encoded, SetAMP() will arrange to bundle
// an AMP-For-Email representation of your message in addition to your html & plain-text content.
func (m *Message) SetAMPHtml(html string) {
m.specific.setAMPHtml(html)
}
func (pm *plainMessage) setAMPHtml(h string) {
pm.ampHtml = h
}
func (mm *mimeMessage) setAMPHtml(_ string) {}
// AddTag attaches tags to the message. Tags are useful for metrics gathering and event tracking purposes.
// Refer to the Mailgun documentation for further details.
func (m *Message) AddTag(tag ...string) error {
if len(m.tags) >= MaxNumberOfTags {
return fmt.Errorf("cannot add any new tags. Message tag limit (%d) reached", MaxNumberOfTags)
}
m.tags = append(m.tags, tag...)
return nil
}
// SetTemplate sets the name of a template stored via the template API.
// See https://documentation.mailgun.com/en/latest/user_manual.html#templating
func (m *Message) SetTemplate(t string) {
m.specific.setTemplate(t)
}
func (pm *plainMessage) setTemplate(t string) {
pm.template = t
}
func (mm *mimeMessage) setTemplate(t string) {}
// AddCampaign is no longer supported and is deprecated for new software.
func (m *Message) AddCampaign(campaign string) {
m.campaigns = append(m.campaigns, campaign)
}
// SetDKIM arranges to send the o:dkim header with the message, and sets its value accordingly.
// Refer to the Mailgun documentation for more information.
func (m *Message) SetDKIM(dkim bool) {
m.dkim = dkim
m.dkimSet = true
}
// EnableNativeSend allows the return path to match the address in the Message.Headers.From:
// field when sending from Mailgun rather than the usual bounce+ address in the return path.
func (m *Message) EnableNativeSend() {
m.nativeSend = true
}
// EnableTestMode allows submittal of a message, such that it will be discarded by Mailgun.
// This facilitates testing client-side software without actually consuming e-mail resources.
func (m *Message) EnableTestMode() {
m.testMode = true
}
// SetDeliveryTime schedules the message for transmission at the indicated time.
// Pass nil to remove any installed schedule.
// Refer to the Mailgun documentation for more information.
func (m *Message) SetDeliveryTime(dt time.Time) {
m.deliveryTime = dt
}
// SetSTOPeriod toggles Send Time Optimization (STO) on a per-message basis.
// String should be set to the number of hours in [0-9]+h format,
// with the minimum being 24h and the maximum being 72h.
// Refer to the Mailgun documentation for more information.
func (m *Message) SetSTOPeriod(stoPeriod string) error {
validPattern := `^([2-6][4-9]|[3-6][0-9]|7[0-2])h$`
match, err := regexp.MatchString(validPattern, stoPeriod)
if err != nil {
return err
}
if !match {
return errors.New("STO period is invalid. Valid range is 24h to 72h")
}
m.stoPeriod = stoPeriod
return nil
}
// SetTracking sets the o:tracking message parameter to adjust, on a message-by-message basis,
// whether or not Mailgun will rewrite URLs to facilitate event tracking.
// Events tracked includes opens, clicks, unsubscribes, etc.
// Note: simply calling this method ensures that the o:tracking header is passed in with the message.
// Its yes/no setting is determined by the call's parameter.
// Note that this header is not passed on to the final recipient(s).
// Refer to the Mailgun documentation for more information.
func (m *Message) SetTracking(tracking bool) {
m.tracking = tracking
m.trackingSet = true
}
// SetTrackingClicks information is found in the Mailgun documentation.
func (m *Message) SetTrackingClicks(trackingClicks bool) {
m.trackingClicks = yesNo(trackingClicks)
m.trackingClicksSet = true
}
// SetTrackingOptions sets the o:tracking, o:tracking-clicks and o:tracking-opens at once.
func (m *Message) SetTrackingOptions(options *TrackingOptions) {
m.tracking = options.Tracking
m.trackingSet = true
m.trackingClicks = options.TrackingClicks
m.trackingClicksSet = true
m.trackingOpens = options.TrackingOpens
m.trackingOpensSet = true
}
// SetRequireTLS information is found in the Mailgun documentation.
func (m *Message) SetRequireTLS(b bool) {
m.requireTLS = b
}
// SetSkipVerification information is found in the Mailgun documentation.
func (m *Message) SetSkipVerification(b bool) {
m.skipVerification = b
}
// SetTrackingOpens information is found in the Mailgun documentation.
func (m *Message) SetTrackingOpens(trackingOpens bool) {
m.trackingOpens = trackingOpens
m.trackingOpensSet = true
}
// SetTemplateVersion information is found in the Mailgun documentation.
func (m *Message) SetTemplateVersion(tag string) {
m.templateVersionTag = tag
}
// SetTemplateRenderText information is found in the Mailgun documentation.
func (m *Message) SetTemplateRenderText(render bool) {
m.templateRenderText = render
}
// AddHeader allows you to send custom MIME headers with the message.
func (m *Message) AddHeader(header, value string) {
if m.headers == nil {
m.headers = make(map[string]string)
}
m.headers[header] = value
}
// AddVariable lets you associate a set of variables with messages you send,
// which Mailgun can use to, in essence, complete form-mail.
// Refer to the Mailgun documentation for more information.
func (m *Message) AddVariable(variable string, value interface{}) error {
if m.variables == nil {
m.variables = make(map[string]string)
}
j, err := json.Marshal(value)
if err != nil {
return err
}
encoded := string(j)
v, err := strconv.Unquote(encoded)
if err != nil {
v = encoded
}
m.variables[variable] = v
return nil
}
// AddTemplateVariable adds a template variable to the map of template variables, replacing the variable if it is already there.
// This is used for server-side message templates and can nest arbitrary values. At send time, the resulting map will be converted into
// a JSON string and sent as a header in the X-Mailgun-Variables header.
func (m *Message) AddTemplateVariable(variable string, value interface{}) error {
if m.templateVariables == nil {
m.templateVariables = make(map[string]interface{})
}
m.templateVariables[variable] = value
return nil
}
// AddDomain allows you to use a separate domain for the type of messages you are sending.
func (m *Message) AddDomain(domain string) {
m.domain = domain
}
// GetHeaders retrieves the http headers associated with this message
func (m *Message) GetHeaders() map[string]string {
return m.headers
}
// ErrInvalidMessage is returned by `Send()` when the `mailgun.Message` struct is incomplete
var ErrInvalidMessage = errors.New("message not valid")
// Send attempts to queue a message (see Message, NewMessage, and its methods) for delivery.
// It returns the Mailgun server response, which consists of two components:
// - A human-readable status message, typically "Queued. Thank you."
// - A Message ID, which is the id used to track the queued message. The message id is useful
// when contacting support to report an issue with a specific message or to relate a
// delivered, accepted or failed event back to specific message.
//
// The status and message ID are only returned if no error occurred.
//
// Error returns can be of type `error.Error` which wrap internal and standard
// golang errors like `url.Error`. The error can also be of type
// mailgun.UnexpectedResponseError which contains the error returned by the mailgun API.
//
// mailgun.UnexpectedResponseError {
// URL: "https://api.mailgun.com/v3/messages",
// Expected: 200,
// Actual: 400,
// Data: "Domain not found: example.com",
// }
//
// See the public mailgun documentation for all possible return codes and error messages
func (mg *MailgunImpl) Send(ctx context.Context, message *Message) (mes string, id string, err error) {
if mg.domain == "" {
err = errors.New("you must provide a valid domain before calling Send()")
return
}
invalidChars := ":&'@(),!?#;%+=<>"
if i := strings.ContainsAny(mg.domain, invalidChars); i {
err = fmt.Errorf("you called Send() with a domain that contains invalid characters")
return
}
if mg.apiKey == "" {
err = errors.New("you must provide a valid api-key before calling Send()")
return
}
if !isValid(message) {
err = ErrInvalidMessage
return
}
if message.stoPeriod != "" && message.RecipientCount() > 1 {
err = errors.New("STO can only be used on a per-message basis")
return
}
payload := newFormDataPayload()
message.specific.addValues(payload)
for _, to := range message.to {
payload.addValue("to", to)
}
for _, tag := range message.tags {
payload.addValue("o:tag", tag)
}
for _, campaign := range message.campaigns {
payload.addValue("o:campaign", campaign)
}
if message.dkimSet {
payload.addValue("o:dkim", yesNo(message.dkim))
}
if !message.deliveryTime.IsZero() {
payload.addValue("o:deliverytime", formatMailgunTime(message.deliveryTime))
}
if message.stoPeriod != "" {
payload.addValue("o:deliverytime-optimize-period", message.stoPeriod)
}
if message.nativeSend {
payload.addValue("o:native-send", "yes")
}
if message.testMode {
payload.addValue("o:testmode", "yes")
}
if message.trackingSet {
payload.addValue("o:tracking", yesNo(message.tracking))
}
if message.trackingClicksSet {
payload.addValue("o:tracking-clicks", message.trackingClicks)
}
if message.trackingOpensSet {
payload.addValue("o:tracking-opens", yesNo(message.trackingOpens))
}
if message.requireTLS {
payload.addValue("o:require-tls", trueFalse(message.requireTLS))
}
if message.skipVerification {
payload.addValue("o:skip-verification", trueFalse(message.skipVerification))
}
if message.headers != nil {
for header, value := range message.headers {
payload.addValue("h:"+header, value)
}
}
if message.variables != nil {
for variable, value := range message.variables {
payload.addValue("v:"+variable, value)
}
}
if message.templateVariables != nil {
variableString, err := json.Marshal(message.templateVariables)
if err == nil {
// the map was marshalled as json so add it
payload.addValue("h:X-Mailgun-Variables", string(variableString))
}
}
if message.recipientVariables != nil {
j, err := json.Marshal(message.recipientVariables)
if err != nil {
return "", "", err
}
payload.addValue("recipient-variables", string(j))
}
if message.attachments != nil {
for _, attachment := range message.attachments {
payload.addFile("attachment", attachment)
}
}
if message.readerAttachments != nil {
for _, readerAttachment := range message.readerAttachments {
payload.addReadCloser("attachment", readerAttachment.Filename, readerAttachment.ReadCloser)
}
}
if message.bufferAttachments != nil {
for _, bufferAttachment := range message.bufferAttachments {
payload.addBuffer("attachment", bufferAttachment.Filename, bufferAttachment.Buffer)
}
}
if message.inlines != nil {
for _, inline := range message.inlines {
payload.addFile("inline", inline)
}
}
if message.readerInlines != nil {
for _, readerAttachment := range message.readerInlines {
payload.addReadCloser("inline", readerAttachment.Filename, readerAttachment.ReadCloser)
}
}
if message.domain == "" {
message.domain = mg.Domain()
}
if message.templateVersionTag != "" {
payload.addValue("t:version", message.templateVersionTag)
}
if message.templateRenderText {
payload.addValue("t:text", yesNo(message.templateRenderText))
}
r := newHTTPRequest(generateApiUrlWithDomain(mg, message.specific.endpoint(), message.domain))
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
// Override any HTTP headers if provided
for k, v := range mg.overrideHeaders {
r.addHeader(k, v)
}
var response sendMessageResponse
err = postResponseFromJSON(ctx, r, payload, &response)
if err == nil {
mes = response.Message
id = response.Id
}
r.mu.RLock()
defer r.mu.RUnlock()
if r.capturedCurlOutput != "" {
mg.mu.Lock()
defer mg.mu.Unlock()
mg.capturedCurlOutput = r.capturedCurlOutput
}
return
}
func (pm *plainMessage) addValues(p *formDataPayload) {
p.addValue("from", pm.from)
p.addValue("subject", pm.subject)
p.addValue("text", pm.text)
for _, cc := range pm.cc {
p.addValue("cc", cc)
}
for _, bcc := range pm.bcc {
p.addValue("bcc", bcc)
}
if pm.html != "" {
p.addValue("html", pm.html)
}
if pm.template != "" {
p.addValue("template", pm.template)
}
if pm.ampHtml != "" {
p.addValue("amp-html", pm.ampHtml)
}
}
func (mm *mimeMessage) addValues(p *formDataPayload) {
p.addReadCloser("message", "message.mime", mm.body)
}
func (pm *plainMessage) endpoint() string {
return messagesEndpoint
}
func (mm *mimeMessage) endpoint() string {
return mimeMessagesEndpoint
}
// yesNo translates a true/false boolean value into a yes/no setting suitable for the Mailgun API.
func yesNo(b bool) string {
if b {
return "yes"
}
return "no"
}
func trueFalse(b bool) string {
if b {
return "true"
}
return "false"
}
// isValid returns true if, and only if,
// a Message instance is sufficiently initialized to send via the Mailgun interface.
func isValid(m *Message) bool {
if m == nil {
return false
}
if !m.specific.isValid() {
return false
}
if m.RecipientCount() == 0 {
return false
}
if !validateStringList(m.tags, false) {
return false
}
if !validateStringList(m.campaigns, false) || len(m.campaigns) > 3 {
return false
}
return true
}
func (pm *plainMessage) isValid() bool {
if !validateStringList(pm.cc, false) {
return false
}
if !validateStringList(pm.bcc, false) {
return false
}
if pm.template != "" {
// pm.text or pm.html not needed if template is supplied
return true
}
if pm.from == "" {
return false
}
if pm.text == "" && pm.html == "" {
return false
}
return true
}
func (mm *mimeMessage) isValid() bool {
return mm.body != nil
}
// validateStringList returns true if, and only if,
// a slice of strings exists AND all of its elements exist,
// OR if the slice doesn't exist AND it's not required to exist.
// The requireOne parameter indicates whether the list is required to exist.
func validateStringList(list []string, requireOne bool) bool {
hasOne := false
if list == nil {
return !requireOne
} else {
for _, a := range list {
if a == "" {
return false
} else {
hasOne = hasOne || true
}
}
}
return hasOne
}
// GetStoredMessage retrieves information about a received e-mail message.
// This provides visibility into, e.g., replies to a message sent to a mailing list.
func (mg *MailgunImpl) GetStoredMessage(ctx context.Context, url string) (StoredMessage, error) {
r := newHTTPRequest(url)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
var response StoredMessage
err := getResponseFromJSON(ctx, r, &response)
return response, err
}
// Given a storage id resend the stored message to the specified recipients
func (mg *MailgunImpl) ReSend(ctx context.Context, url string, recipients ...string) (string, string, error) {
r := newHTTPRequest(url)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
payload := newFormDataPayload()
if len(recipients) == 0 {
return "", "", errors.New("must provide at least one recipient")
}
for _, to := range recipients {
payload.addValue("to", to)
}
var resp sendMessageResponse
err := postResponseFromJSON(ctx, r, payload, &resp)
if err != nil {
return "", "", err
}
return resp.Message, resp.Id, nil
}
// GetStoredMessageRaw retrieves the raw MIME body of a received e-mail message.
// Compared to GetStoredMessage, it gives access to the unparsed MIME body, and
// thus delegates to the caller the required parsing.
func (mg *MailgunImpl) GetStoredMessageRaw(ctx context.Context, url string) (StoredMessageRaw, error) {
r := newHTTPRequest(url)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
r.addHeader("Accept", "message/rfc2822")
var response StoredMessageRaw
err := getResponseFromJSON(ctx, r, &response)
return response, err
}
// Deprecated: Use GetStoreMessage() instead
func (mg *MailgunImpl) GetStoredMessageForURL(ctx context.Context, url string) (StoredMessage, error) {
return mg.GetStoredMessage(ctx, url)
}
// Deprecated: Use GetStoreMessageRaw() instead
func (mg *MailgunImpl) GetStoredMessageRawForURL(ctx context.Context, url string) (StoredMessageRaw, error) {
return mg.GetStoredMessageRaw(ctx, url)
}
// GetStoredAttachment retrieves the raw MIME body of a received e-mail message attachment.
func (mg *MailgunImpl) GetStoredAttachment(ctx context.Context, url string) ([]byte, error) {
r := newHTTPRequest(url)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
r.addHeader("Accept", "message/rfc2822")
response, err := makeGetRequest(ctx, r)
if err != nil {
return nil, err
}
return response.Data, err
}