-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWireMailSendGrid.module.php
More file actions
839 lines (547 loc) · 20.1 KB
/
WireMailSendGrid.module.php
File metadata and controls
839 lines (547 loc) · 20.1 KB
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
<?php
/**
* WireMailSendGrid
* Extend WireMail to bypass PHP Mail and send mail via SendGrids Web API
*
*/
class WireMailSendGrid extends WireMail implements Module, ConfigurableModule {
/**
* log file names
*
*/
const SUCCESS_LOG = 'wiremail-sendgrid';
const ERROR_LOG = 'wiremail-sendgrid-errors';
// SendGrid email instance
// Access this to set features directly on the instance
// https://github.com/sendgrid/sendgrid-php/
// this is an instance of \SendGrid\Mail\Mail()
public $email = null;
// SendGrid template ID
protected $templateId = '';
// SendGrid dynamic template data
protected $dynamicTemplateData = [];
// SendGrid custom args
protected $customArgs = [];
// SendGrid sections
protected $sections = [];
// SendGrid categories
protected $categories = [];
/**
* Initialize the module
*
*/
public function init() {
// get the SendGrid Classes
//----------------------------------
require_once( __DIR__ . '/sendgrid-php/sendgrid-php.php' );
// set up an email with SendGrids PHP API
//----------------------------------
$this->email = new \SendGrid\Mail\Mail();
// Add additional keys to mail
//----------------------------------
// fallback for older versions of WireMail
if (!isset($this->mail['attachments'])) $this->mail['attachments'] = [];
if (!isset($this->mail['cc'])) $this->mail['cc'] = [];
if (!isset($this->mail['bcc'])) $this->mail['bcc'] = [];
// Set Default Email Config
//----------------------------------
$this->setDefaultConfig();
}
/**
* Set up any config values stored on the module
*
*/
protected function setDefaultConfig()
{
// Click Tracking Settings
//----------------------------------
if ($this->sendGridClickTrackingEnable) {
$this->email->setClickTracking(
true,
!!($this->sendGridClickTrackingEnableText)
);
}
// Open Tracking Settings
//----------------------------------
if ($this->sendGridOpenTrackingEnable) {
$this->email->setOpenTracking(
true,
$this->sendGridOpenTrackingSubstitutionTag
? $this->sendGridOpenTrackingSubstitutionTag
: null
);
}
// Subscription Tracking Settings
//----------------------------------
if ($this->sendGridSubscriptionTrackingEnable) {
$this->email->setSubscriptionTracking(
true,
$this->sendGridSubscriptionTrackingText
? $this->sendGridSubscriptionTrackingText
: null,
$this->sendGridSubscriptionTrackingHTML
? $this->sendGridSubscriptionTrackingHTML
: null,
$this->sendGridSubscriptionTrackingSubstitutionTag
? $this->sendGridSubscriptionTrackingSubstitutionTag
: null
);
}
// Subscription Tracking Settings
//----------------------------------
if ($this->sendGridAnalyticsEnable) {
$this->email->setGanalytics(
true,
$this->sendGridAnalyticsUtmSource
? $this->sendGridAnalyticsUtmSource
: null,
$this->sendGridAnalyticsUtmMedium
? $this->sendGridAnalyticsUtmMedium
: null,
$this->sendGridAnalyticsUtmTerm
? $this->sendGridAnalyticsUtmTerm
: null,
$this->sendGridAnalyticsUtmContent
? $this->sendGridAnalyticsUtmContent
: null,
$this->sendGridAnalyticsUtmCampaign
? $this->sendGridAnalyticsUtmCampaign
: null
);
}
// Sandbox
//----------------------------------
if ($this->sendGridSandbox) $this->email->enableSandBoxMode();
}
/**
* Prevent the use of WireMail and Process the send via SendGrid Web API
* @return {int} a positive number (indicating number of addresses emailed) or 0 on failure
*
*/
public function ___send()
{
// set the subject
//----------------------------------
$this->email->setSubject($this->subject);
// set a from address
//----------------------------------
$fromEmail = $this->from ? $this->from : $this->sendGridFromEmail;
$fromName = $this->fromName ? $this->fromName : '';
if (!$fromName
&& $fromEmail === $this->sendGridFromEmail
&& $this->sendGridFromName) {
$fromName = $this->sendGridFromName;
}
$this->email->setFrom($fromEmail, $fromName);
// set a reply to address if different to from
//----------------------------------
$replyToEmail = $this->mail['replyTo'] ? $this->mail['replyTo'] : $this->sendGridReplyToEmail;
if (!$replyToEmail) $replyToEmail = $fromEmail;
$replyToName = $this->mail['replyToName'] ? $this->mail['replyToName'] : '';
if (!$replyToName
&& $replyToEmail === $this->sendGridReplyToEmail
&& $this->sendGridReplyToName) {
$replyToName = $this->sendGridReplyToName;
}
if ($replyToEmail !== $fromEmail
|| $replyToName !== $fromName) {
$this->email->setReplyTo($replyToEmail, $replyToName);
}
// set the mail body - html and text
//----------------------------------
if ($this->body) {
$this->email->addContent('text/plain', $this->body);
}
if ($this->bodyHTML) {
$this->email->addContent('text/html', $this->bodyHTML);
}
// set any cc
//----------------------------------
if (count($this->mail['cc'])) {
foreach ($this->mail['cc'] as $cc) {
$this->email->addCc($cc['email'], $cc['name'], $cc['substitutions']);
}
}
// set any bcc
//----------------------------------
if (count($this->mail['bcc'])) {
foreach ($this->mail['bcc'] as $bcc) {
$this->email->addBcc($bcc['email'], $bcc['name'], $bcc['substitutions']);
}
}
// set any attachments
//----------------------------------
if (count($this->mail['attachments'])) {
foreach ($this->mail['attachments'] as $attachmentPayload) {
$filename = $this->wire('sanitizer')->text($attachmentPayload['filename'], [
'maxLength' => 512,
'truncateTail' => false,
'stripSpace' => '-',
'stripQuotes' => true
]);
if(!$filename) continue;
$content = base64_encode(file_get_contents($attachmentPayload['path']));
if(!$content) continue;
$mimeType = mime_content_type($filename);
if(!$mimeType) continue;
$this->email->addAttachment(
$content,
$mimeType,
$filename,
$attachmentPayload['disposition'],
$attachmentPayload['contentId']
);
}
}
// add headers
//----------------------------------
foreach ($this->mail['header'] as $key => $value) {
$this->email->addHeader($key, $value);
}
// set 'to' addresses
//----------------------------------
// retain WireMail $numSent as return value
$numSent = 0;
foreach ($this->mail['to'] as $to) {
$this->email->addTo($to['email'], $to['name'], $to['substitutions']);
$numSent++;
}
// Set any dynamic template data
//----------------------------------
if (count($this->dynamicTemplateData)) {
$this->email->addDynamicTemplateDatas($this->dynamicTemplateData);
}
// Set any custom args
//----------------------------------
if (count($this->customArgs)) {
$this->email->addCustomArgs($this->customArgs);
}
// Set any sections
//----------------------------------
if (count($this->sections)) {
$this->email->addSections($this->sections);
}
// Create instance of authenticated SendGrid API
//----------------------------------
$sendgrid = new \SendGrid($this->sendGridApiKey);
try {
$response = $sendgrid->send($this->email);
$statusCode = $response->statusCode();
$message = $statusCode;
if ($response->body()) $message .= ': ' . $response->body();
if ($statusCode >= 300) {
$this->log->save(self::ERROR_LOG, $message);
} else if ($this->sendGridLogSuccess) {
$this->log->save(self::SUCCESS_LOG, $message);
}
} catch (Exception $e) {
$numSent = 0;
$this->log->save(self::ERROR_LOG, $e->getMessage());
}
// replicate WireMail return value
//----------------------------------
return $numSent;
}
/**
* process the passed payload and assign to the mail key
* use the email address as a key for the associated array
* @param {string} $mailKey - the key to assign
* @param {string} $email - email address
* @param {string} $name - name of the person associated with the email
* @param {array|null} $substitutions - key/value substitutions to be be applied to an email template
* @param {string} $subject - personalized subject of the email
* @return $this
* @throws WireException if you attempt to set an invlaid mail key
*
*/
protected function addEmailPayload(
$mailKey = '',
$email = '',
$name = '',
$substitutions = null,
$subject = null
) {
if (!$mailKey
|| !isset($this->mail[$mailKey])
|| !is_array($this->mail[$mailKey])) {
throw new WireException("mail key not a valid array: $mailKey");
}
$email = $this->sanitizeEmail($email);
$name = $this->wire('sanitizer')->text($name);
if ($subject && is_string($subject)) {
$substitutions = [
'subject' => $subject,
];
}
if ($email) {
$this->mail[$mailKey][$email] = [
'email' => $email,
'name' => $name,
'substitutions' => $substitutions,
];
}
return $this;
}
/**
* Support WireMail feature albeit with the requirement for the email to be passed
* @param {string} $mailKey - the key to assign
* @param {string} $name - name of the person associated with the email
* @param {string} $email - email address
* @return $this
* @throws WireException if you attempt to set an invlaid mail key
*
*/
protected function addEmailName(
$mailKey = '',
$name = '',
$email = ''
) {
if (!$mailKey
|| !isset($this->mail[$mailKey])
|| !is_array($this->mail[$mailKey])) {
throw new WireException("mail key not a valid array: $mailKey");
}
if ($name
&& $email
&& $this->mail[$mailKey][$email]) {
$this->mail[$mailKey][$email]['name'] = $name;
}
return $this;
}
/**
* set to
* @param {string} $email - email address
* @param {string} $name - name of the person associated with the email
* @param {array|null} $substitutions - key/value substitutions to be be applied to an email template
* @param {string|null} $subject - personalized subject of the email
* @return $this
*
*/
public function to($email = '', $name = '', $substitutions = null, $subject = null)
{
// WireMail clears existing values if email is null
//----------------------------------
if (!$email) {
$this->mail['to'] = [];
return $this;
}
// convert email & name to array to support WireMail
//----------------------------------
$emails = is_array($email) ? $email : explode(',', $email);
$names = is_array($name) ? $name : explode(',', $name);
foreach ($emails as $index => $value) {
$this->addEmailPayload('to', $emails[$index], $names[$index], $substitutions, $subject);
}
return $this;
}
/**
* Set the 'to' name - 'to' is an associated array keyed by email
*
* @param {string} $name - name of the person associated with the email
* @param {string} $email - email address
* @return $this
*
*/
public function toName($name = '', $email = '') {
return $this->addEmailName('to', $name, $email);
}
/**
* set CC
* @param {string} $email - email address
* @param {string} $name - name of the person associated with the email
* @param {array|null} $substitutions - key/value substitutions to be be applied to an email template
* @param {string|null} $subject - personalized subject of the email
* @return $this
*
*/
public function cc($email = '', $name = '', $substitutions = null, $subject = null)
{
return $this->addEmailPayload('cc', $email, $name, $substitutions, $subject);
}
/**
* Set the 'cc' name - 'cc' is an associated array keyed by email
*
* @param {string} $name - name of the person associated with the email
* @param {string} $email - email address
* @return $this
*
*/
public function ccName($name = '', $email = '') {
return $this->addEmailName('cc', $name, $email);
}
/**
* set BCC
* @param {string} $email - email address
* @param {string} $name - name of the person associated with the email
* @param {array|null} $substitutions - key/value substitutions to be be applied to an email template
* @param {string|null} $subject - personalized subject of the email
* @return $this
*
*/
public function bcc($email = '', $name = '', $substitutions = null, $subject = null)
{
return $this->addEmailPayload('bcc', $email, $name, $substitutions, $subject);
}
/**
* Set the 'bcc' name - 'bcc' is an associated array keyed by email
*
* @param {string} $name - name of the person associated with the email
* @param {string} $email - email address
* @return $this
*
*/
public function bccName($name = '', $email = '') {
return $this->addEmailName('bcc', $name, $email);
}
/**
* Add ReplyTo for older versions of ProcessWire (v2)
* @param {String} $email - email address
* @param {String} $name - name of the person associated with the email
* @return $this
*
*/
public function replyTo($email = '', $name = '')
{
$email = $this->sanitizeEmail($email);
if ($email) $this->mail['replyTo'] = $email;
$name = $this->wire('sanitizer')->text($name);
if ($name) $this->mail['replyToName'] = $name;
return $this;
}
/**
* Add Attachments - provides fallback for older versions and adds SendGrid type and id
* @param {string} $path - Full path and filename of file attachment
* @param {string} $filename - Optional different basename for file as it appears in the mail
* @param {string|null} $disposition - How the attachment should be displayed: inline or attachment
* @param {string|null} $contentId - Used when disposition is inline to diplay the file within the body of the email
* @return $this
*
*/
public function attachment(
$path = '',
$filename = '',
$disposition = null,
$contentId = null
) {
if (is_null($path)) {
$this->mail['attachments'] = [];
} else if (is_file($path)) {
if (!$filename) $filename = basename($path);
$this->mail['attachments'][$filename] = [
'path' => $path,
'filename' => $filename,
'disposition' => $disposition,
'contentId' => $contentId,
];
}
return $this;
}
/**
* Set a SendGrid Template ID
* @param {string} $id - SendGrid template ID
* @return $this
* @throws WireException if ID not a string
*
*/
public function setTemplateId($id = '')
{
if (!is_string($id)) throw new WireException('template ID must be of type string.');
$this->email->setTemplateId($id);
return $this;
}
/**
* Set a SendGrid Dynamic Template Substitution
* @param {String} $name
* @param {String|Array|Object|Boolean|Integer|null} $value - if null unset the key
* @return $this
* @throws WireException if name not a string
*
*/
public function setDynamicTemplateData($name = '', $value = '')
{
if (!is_string($name)) throw new WireException('dynamic template name/key must be of type string.');
if (!$value) {
unset($this->dynamicTemplateData[$name]);
} else {
$this->dynamicTemplateData[$name] = $value;
}
return $this;
}
/**
* Set a SendGrid Custom Arg
* @param {String} $name
* @param {String|null} $value - if null unset the key
* @return $this
* @throws WireException if name not a string
*
*/
public function setCustomArg($name = '', $value = '')
{
if (!is_string($name)) throw new WireException('Custom Arg name/key must be of type string.');
if (!is_string($value)
|| !$value) {
unset($this->customArgs[$name]);
} else {
$this->customArgs[$name] = $value;
}
return $this;
}
/**
* Set a SendGrid section
* @param {String} $name - Section name/key
* @param {String|null} $value - section value - if null unset the key
* @return $this
* @throws WireException if name not a string
*
*/
public function setSection($name = '', $value = '')
{
if (!is_string($name)) throw new WireException('Section name/key must be of type string.');
if (!is_string($value)
|| !$value) {
unset($this->sections[$name]);
} else {
$this->sections[$name] = $value;
}
return $this;
}
/**
* Add a SendGrid category
* @param {String} $category - category name
* @return $this
* @throws WireException if category not a string
*
*/
public function addCategory($category = '')
{
if (!is_string($category)) throw new WireException('category must be of type string.');
$this->email->addCategory($category);
return $this;
}
/**
* Set a SendGrid sendAt value
*
* @param {int} $sendAt - unix timestamp, when you want your email to be delivered. (no more than 72hrs away)
* @return $this
* @throws WireException if $sendAt not an int
*/
public function setSendAt($sendAt)
{
if (!is_int($sendAt)) throw new WireException('$sendAt must be of type int.');
$this->email->setSendAt($sendAt);
return $this;
}
/**
* Add the a batch ID value - ID represents a batch of emails to be sent at the same time
*
* @param {String} $batchId - SendGrid Batch ID
* @return $this
* @throws WireException if $batchId not a string
*/
public function setBatchId($batchId)
{
if (!is_string($batchId)) throw new WireException('$batchId must be of type string.');
$this->email->setBatchId($batchId);
return $this;
}
}