-
Notifications
You must be signed in to change notification settings - Fork 824
/
Email.php
885 lines (771 loc) · 20.9 KB
/
Email.php
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
<?php
namespace SilverStripe\Control\Email;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTP;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\View\Requirements;
use SilverStripe\View\SSViewer;
use SilverStripe\View\ThemeResourceLoader;
use SilverStripe\View\ViewableData;
use Swift_Message;
use Swift_MimePart;
/**
* Class to support sending emails.
*/
class Email extends ViewableData
{
/**
* @var array
* @config
*/
private static $send_all_emails_to = array();
/**
* @var array
* @config
*/
private static $cc_all_emails_to = array();
/**
* @var array
* @config
*/
private static $bcc_all_emails_to = array();
/**
* @var array
* @config
*/
private static $send_all_emails_from = array();
/**
* This will be set in the config on a site-by-site basis
*
* @config
* @var string The default administrator email address.
*/
private static $admin_email = null;
/**
* @var Swift_Message
*/
private $swiftMessage;
/**
* @var string The name of the HTML template to render the email with (without *.ss extension)
*/
private $HTMLTemplate = null;
/**
* @var string The name of the plain text template to render the plain part of the email with
*/
private $plainTemplate = null;
/**
* @var Swift_MimePart
*/
private $plainPart;
/**
* @var array|ViewableData Additional data available in a template.
* Used in the same way than {@link ViewableData->customize()}.
*/
private $data = array();
/**
* @var array
*/
private $failedRecipients = array();
/**
* Checks for RFC822-valid email format.
*
* @param string $address
* @return boolean
*
* @copyright Cal Henderson <[email protected]>
* This code is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
* http://creativecommons.org/licenses/by-sa/2.5/
*/
public static function is_valid_address($address)
{
return \Swift_Validate::email($address);
}
/**
* Get send_all_emails_to
*
* @return array Keys are addresses, values are names
*/
public static function getSendAllEmailsTo()
{
return static::mergeConfiguredEmails('send_all_emails_to', 'SS_SEND_ALL_EMAILS_TO');
}
/**
* Get cc_all_emails_to
*
* @return array
*/
public static function getCCAllEmailsTo()
{
return static::mergeConfiguredEmails('cc_all_emails_to', 'SS_CC_ALL_EMAILS_TO');
}
/**
* Get bcc_all_emails_to
*
* @return array
*/
public static function getBCCAllEmailsTo()
{
return static::mergeConfiguredEmails('bcc_all_emails_to', 'SS_BCC_ALL_EMAILS_TO');
}
/**
* Get send_all_emails_from
*
* @return array
*/
public static function getSendAllEmailsFrom()
{
return static::mergeConfiguredEmails('send_all_emails_from', 'SS_SEND_ALL_EMAILS_FROM');
}
/**
* Normalise email list from config merged with env vars
*
* @param string $config Config key
* @param string $env Env variable key
* @return array Array of email addresses
*/
protected static function mergeConfiguredEmails($config, $env)
{
// Normalise config list
$normalised = [];
$source = (array)static::config()->get($config);
foreach ($source as $address => $name) {
if ($address && !is_numeric($address)) {
$normalised[$address] = $name;
} elseif ($name) {
$normalised[$name] = null;
}
}
$extra = Environment::getEnv($env);
if ($extra) {
$normalised[$extra] = null;
}
return $normalised;
}
/**
* Encode an email-address to protect it from spambots.
* At the moment only simple string substitutions,
* which are not 100% safe from email harvesting.
*
* @param string $email Email-address
* @param string $method Method for obfuscating/encoding the address
* - 'direction': Reverse the text and then use CSS to put the text direction back to normal
* - 'visible': Simple string substitution ('@' to '[at]', '.' to '[dot], '-' to [dash])
* - 'hex': Hexadecimal URL-Encoding - useful for mailto: links
* @return string
*/
public static function obfuscate($email, $method = 'visible')
{
switch ($method) {
case 'direction':
Requirements::customCSS('span.codedirection { unicode-bidi: bidi-override; direction: rtl; }', 'codedirectionCSS');
return '<span class="codedirection">' . strrev($email) . '</span>';
case 'visible':
$obfuscated = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
return strtr($email, $obfuscated);
case 'hex':
$encoded = '';
for ($x = 0; $x < strlen($email); $x++) {
$encoded .= '&#x' . bin2hex($email{$x}) . ';';
}
return $encoded;
default:
user_error('Email::obfuscate(): Unknown obfuscation method', E_USER_NOTICE);
return $email;
}
}
/**
* Email constructor.
* @param string|array|null $from
* @param string|array|null $to
* @param string|null $subject
* @param string|null $body
* @param string|array|null $cc
* @param string|array|null $bcc
* @param string|null $returnPath
*/
public function __construct(
$from = null,
$to = null,
$subject = null,
$body = null,
$cc = null,
$bcc = null,
$returnPath = null
) {
if ($from) {
$this->setFrom($from);
}
if ($to) {
$this->setTo($to);
}
if ($subject) {
$this->setSubject($subject);
}
if ($body) {
$this->setBody($body);
}
if ($cc) {
$this->setCC($cc);
}
if ($bcc) {
$this->setBCC($bcc);
}
if ($returnPath) {
$this->setReturnPath($returnPath);
}
parent::__construct();
}
/**
* @return Swift_Message
*/
public function getSwiftMessage()
{
if (!$this->swiftMessage) {
$this->setSwiftMessage(new Swift_Message(null, null, 'text/html', 'utf-8'));
}
return $this->swiftMessage;
}
/**
* @param Swift_Message $swiftMessage
*
* @return $this
*/
public function setSwiftMessage($swiftMessage)
{
$swiftMessage->setDate(DBDatetime::now()->getTimestamp());
if (!$swiftMessage->getFrom() && ($defaultFrom = $this->config()->get('admin_email'))) {
$swiftMessage->setFrom($defaultFrom);
}
$this->swiftMessage = $swiftMessage;
return $this;
}
/**
* @return string[]
*/
public function getFrom()
{
return $this->getSwiftMessage()->getFrom();
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function setFrom($address, $name = null)
{
$this->getSwiftMessage()->setFrom($address, $name);
return $this;
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function addFrom($address, $name = null)
{
$this->getSwiftMessage()->addFrom($address, $name);
return $this;
}
/**
* @return string
*/
public function getSender()
{
return $this->getSwiftMessage()->getSender();
}
/**
* @param string $address
* @param string|null $name
* @return $this
*/
public function setSender($address, $name = null)
{
$this->getSwiftMessage()->setSender($address, $name);
return $this;
}
/**
* @return string
*/
public function getReturnPath()
{
return $this->getSwiftMessage()->getReturnPath();
}
/**
* The bounce handler address
*
* @param string $address Email address where bounce notifications should be sent
* @return $this
*/
public function setReturnPath($address)
{
$this->getSwiftMessage()->setReturnPath($address);
return $this;
}
/**
* @return array
*/
public function getTo()
{
return $this->getSwiftMessage()->getTo();
}
/**
* Set recipient(s) of the email
*
* To send to many, pass an array:
* array('[email protected]' => 'My Name', '[email protected]');
*
* @param string|array $address The message recipient(s) - if sending to multiple, use an array of address => name
* @param string|null $name The name of the recipient (if one)
* @return $this
*/
public function setTo($address, $name = null)
{
$this->getSwiftMessage()->setTo($address, $name);
return $this;
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function addTo($address, $name = null)
{
$this->getSwiftMessage()->addTo($address, $name);
return $this;
}
/**
* @return array
*/
public function getCC()
{
return $this->getSwiftMessage()->getCc();
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function setCC($address, $name = null)
{
$this->getSwiftMessage()->setCc($address, $name);
return $this;
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function addCC($address, $name = null)
{
$this->getSwiftMessage()->addCc($address, $name);
return $this;
}
/**
* @return array
*/
public function getBCC()
{
return $this->getSwiftMessage()->getBcc();
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function setBCC($address, $name = null)
{
$this->getSwiftMessage()->setBcc($address, $name);
return $this;
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function addBCC($address, $name = null)
{
$this->getSwiftMessage()->addBcc($address, $name);
return $this;
}
public function getReplyTo()
{
return $this->getSwiftMessage()->getReplyTo();
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function setReplyTo($address, $name = null)
{
$this->getSwiftMessage()->setReplyTo($address, $name);
return $this;
}
/**
* @param string|array $address
* @param string|null $name
* @return $this
*/
public function addReplyTo($address, $name = null)
{
$this->getSwiftMessage()->addReplyTo($address, $name);
return $this;
}
/**
* @return string
*/
public function getSubject()
{
return $this->getSwiftMessage()->getSubject();
}
/**
* @param string $subject The Subject line for the email
* @return $this
*/
public function setSubject($subject)
{
$this->getSwiftMessage()->setSubject($subject);
return $this;
}
/**
* @return int
*/
public function getPriority()
{
return $this->getSwiftMessage()->getPriority();
}
/**
* @param int $priority
* @return $this
*/
public function setPriority($priority)
{
$this->getSwiftMessage()->setPriority($priority);
return $this;
}
/**
* @param string $path Path to file
* @param string $alias An override for the name of the file
* @param string $mime The mime type for the attachment
* @return $this
*/
public function addAttachment($path, $alias = null, $mime = null)
{
$attachment = \Swift_Attachment::fromPath($path);
if ($alias) {
$attachment->setFilename($alias);
}
if ($mime) {
$attachment->setContentType($mime);
}
$this->getSwiftMessage()->attach($attachment);
return $this;
}
/**
* @param string $data
* @param string $name
* @param string $mime
* @return $this
*/
public function addAttachmentFromData($data, $name, $mime = null)
{
$attachment = new \Swift_Attachment($data, $name);
if ($mime) {
$attachment->setContentType($mime);
}
$this->getSwiftMessage()->attach($attachment);
return $this;
}
/**
* @return array|ViewableData The template data
*/
public function getData()
{
return $this->data;
}
/**
* @param array|ViewableData $data The template data to set
* @return $this
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* @param string|array $name The data name to add or array to names => value
* @param string|null $value The value of the data to add
* @return $this
*/
public function addData($name, $value = null)
{
if (is_array($name)) {
$this->data = array_merge($this->data, $name);
} elseif (is_array($this->data)) {
$this->data[$name] = $value;
} else {
$this->data->$name = $value;
}
return $this;
}
/**
* Remove a datum from the message
*
* @param string $name
* @return $this
*/
public function removeData($name)
{
if (is_array($this->data)) {
unset($this->data[$name]);
} else {
$this->data->$name = null;
}
return $this;
}
/**
* @return string
*/
public function getBody()
{
return $this->getSwiftMessage()->getBody();
}
/**
* @param string $body The email body
* @return $this
*/
public function setBody($body)
{
$plainPart = $this->findPlainPart();
if ($plainPart) {
$this->getSwiftMessage()->detach($plainPart);
}
unset($plainPart);
$body = HTTP::absoluteURLs($body);
$this->getSwiftMessage()->setBody($body);
return $this;
}
/**
* @return string The base URL for the email
*/
public function BaseURL()
{
return Director::absoluteBaseURL();
}
/**
* Debugging help
*
* @return string Debug info
*/
public function debug()
{
$this->render();
$class = static::class;
return "<h2>Email template {$class}:</h2>\n" . '<pre>' . $this->getSwiftMessage()->toString() . '</pre>';
}
/**
* @return string
*/
public function getHTMLTemplate()
{
if ($this->HTMLTemplate) {
return $this->HTMLTemplate;
}
return ThemeResourceLoader::inst()->findTemplate(
SSViewer::get_templates_by_class(static::class, '', self::class),
SSViewer::get_themes()
);
}
/**
* Set the template to render the email with
*
* @param string $template
* @return $this
*/
public function setHTMLTemplate($template)
{
if (substr($template, -3) == '.ss') {
$template = substr($template, 0, -3);
}
$this->HTMLTemplate = $template;
return $this;
}
/**
* Get the template to render the plain part with
*
* @return string
*/
public function getPlainTemplate()
{
return $this->plainTemplate;
}
/**
* Set the template to render the plain part with
*
* @param string $template
* @return $this
*/
public function setPlainTemplate($template)
{
if (substr($template, -3) == '.ss') {
$template = substr($template, 0, -3);
}
$this->plainTemplate = $template;
return $this;
}
/**
* @param array $recipients
* @return $this
*/
public function setFailedRecipients($recipients)
{
$this->failedRecipients = $recipients;
return $this;
}
/**
* @return array
*/
public function getFailedRecipients()
{
return $this->failedRecipients;
}
/**
* Used by {@link SSViewer} templates to detect if we're rendering an email template rather than a page template
*
* @return bool
*/
public function IsEmail()
{
return true;
}
/**
* Send the message to the recipients
*
* @return bool true if successful or array of failed recipients
*/
public function send()
{
if (!$this->getBody()) {
$this->render();
}
if (!$this->hasPlainPart()) {
$this->generatePlainPartFromBody();
}
return Injector::inst()->get(Mailer::class)->send($this);
}
/**
* @return array|bool
*/
public function sendPlain()
{
if (!$this->hasPlainPart()) {
$this->render(true);
}
return Injector::inst()->get(Mailer::class)->send($this);
}
/**
* Render the email
* @param bool $plainOnly Only render the message as plain text
* @return $this
*/
public function render($plainOnly = false)
{
if ($existingPlainPart = $this->findPlainPart()) {
$this->getSwiftMessage()->detach($existingPlainPart);
}
unset($existingPlainPart);
// Respect explicitly set body
$htmlPart = $plainOnly ? null : $this->getBody();
$plainPart = $plainOnly ? $this->getBody() : null;
// Ensure we can at least render something
$htmlTemplate = $this->getHTMLTemplate();
$plainTemplate = $this->getPlainTemplate();
if (!$htmlTemplate && !$plainTemplate && !$plainPart && !$htmlPart) {
return $this;
}
// Do not interfere with emails styles
Requirements::clear();
// Render plain part
if ($plainTemplate && !$plainPart) {
$plainPart = $this->renderWith($plainTemplate, $this->getData());
}
// Render HTML part, either if sending html email, or a plain part is lacking
if (!$htmlPart && $htmlTemplate && (!$plainOnly || empty($plainPart))) {
$htmlPart = $this->renderWith($htmlTemplate, $this->getData());
}
// Plain part fails over to generated from html
if (!$plainPart && $htmlPart) {
/** @var DBHTMLText $htmlPartObject */
$htmlPartObject = DBField::create_field('HTMLFragment', $htmlPart);
$plainPart = $htmlPartObject->Plain();
}
// Rendering is finished
Requirements::restore();
// Fail if no email to send
if (!$plainPart && !$htmlPart) {
return $this;
}
// Build HTML / Plain components
if ($htmlPart && !$plainOnly) {
$this->setBody($htmlPart);
$this->getSwiftMessage()->setContentType('text/html');
$this->getSwiftMessage()->setCharset('utf-8');
if ($plainPart) {
$this->getSwiftMessage()->addPart($plainPart, 'text/plain', 'utf-8');
}
} else {
if ($plainPart) {
$this->setBody($plainPart);
}
$this->getSwiftMessage()->setContentType('text/plain');
$this->getSwiftMessage()->setCharset('utf-8');
}
return $this;
}
/**
* @return Swift_MimePart|false
*/
public function findPlainPart()
{
foreach ($this->getSwiftMessage()->getChildren() as $child) {
if ($child instanceof Swift_MimePart && $child->getContentType() == 'text/plain') {
return $child;
}
}
return false;
}
/**
* @return bool
*/
public function hasPlainPart()
{
if ($this->getSwiftMessage()->getContentType() === 'text/plain') {
return true;
}
return (bool) $this->findPlainPart();
}
/**
* Automatically adds a plain part to the email generated from the current Body
*
* @return $this
*/
public function generatePlainPartFromBody()
{
$plainPart = $this->findPlainPart();
if ($plainPart) {
$this->getSwiftMessage()->detach($plainPart);
}
unset($plainPart);
$this->getSwiftMessage()->addPart(
Convert::xml2raw($this->getBody()),
'text/plain',
'utf-8'
);
return $this;
}
}