-
Notifications
You must be signed in to change notification settings - Fork 78
/
fEmail.php
1805 lines (1520 loc) · 56.2 KB
/
fEmail.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
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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Allows creating and sending a single email containing plaintext, HTML, attachments and S/MIME encryption
*
* Please note that this class uses the [http://php.net/function.mail mail()]
* function by default. Developers that are sending multiple emails, or need
* SMTP support, should use fSMTP with this class.
*
* This class is implemented to use the UTF-8 character encoding. Please see
* http://flourishlib.com/docs/UTF-8 for more information.
*
* @copyright Copyright (c) 2008-2011 Will Bond, others
* @author Will Bond [wb] <[email protected]>
* @author Bill Bushee, iMarc LLC [bb-imarc] <[email protected]>
* @author netcarver [n] <[email protected]>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fEmail
*
* @version 1.0.0b30
* @changes 1.0.0b30 Changed methods to return instance for method chaining [n, 2011-09-12]
* @changes 1.0.0b29 Changed ::combineNameEmail() to be a static method and to be exposed publicly for use by other classes [wb, 2011-07-26]
* @changes 1.0.0b28 Fixed ::addAttachment() and ::addRelatedFile() to properly handle duplicate filenames [wb, 2011-05-17]
* @changes 1.0.0b27 Fixed a bug with generating FQDNs on some Windows machines [wb, 2011-02-24]
* @changes 1.0.0b26 Added ::addCustomerHeader() [wb, 2011-02-02]
* @changes 1.0.0b25 Fixed a bug with finding the FQDN on non-Windows machines [wb, 2011-01-19]
* @changes 1.0.0b24 Backwards Compatibility Break - the `$contents` parameter of ::addAttachment() is now first instead of third, ::addAttachment() will now accept fFile objects for the `$contents` parameter, added ::addRelatedFile() [wb, 2010-12-01]
* @changes 1.0.0b23 Fixed a bug on Windows where emails starting with a `.` would have the `.` removed [wb, 2010-09-11]
* @changes 1.0.0b22 Revamped the FQDN code and added ::getFQDN() [wb, 2010-09-07]
* @changes 1.0.0b21 Added a check to prevent permissions warnings when getting the FQDN on Windows machines [wb, 2010-09-02]
* @changes 1.0.0b20 Fixed ::send() to only remove the name of a recipient when dealing with the `mail()` function on Windows and to leave it when using fSMTP [wb, 2010-06-22]
* @changes 1.0.0b19 Changed ::send() to return the message id for the email, fixed the email regexes to require [] around IPs [wb, 2010-05-05]
* @changes 1.0.0b18 Fixed the name of the static method ::unindentExpand() [wb, 2010-04-28]
* @changes 1.0.0b17 Added the static method ::unindentExpand() [wb, 2010-04-26]
* @changes 1.0.0b16 Added support for sending emails via fSMTP [wb, 2010-04-20]
* @changes 1.0.0b15 Added the `$unindent_expand_constants` parameter to ::setBody(), added ::loadBody() and ::loadHTMLBody(), fixed HTML emails with attachments [wb, 2010-03-14]
* @changes 1.0.0b14 Changed ::send() to not double `.`s at the beginning of lines on Windows since it seemed to break things rather than fix them [wb, 2010-03-05]
* @changes 1.0.0b13 Fixed the class to work when safe mode is turned on [wb, 2009-10-23]
* @changes 1.0.0b12 Removed duplicate MIME-Version headers that were being included in S/MIME encrypted emails [wb, 2009-10-05]
* @changes 1.0.0b11 Updated to use the new fValidationException API [wb, 2009-09-17]
* @changes 1.0.0b10 Fixed a bug with sending both an HTML and a plaintext body [bb-imarc, 2009-06-18]
* @changes 1.0.0b9 Fixed a bug where the MIME headers were not being set for all emails [wb, 2009-06-12]
* @changes 1.0.0b8 Added the method ::clearRecipients() [wb, 2009-05-29]
* @changes 1.0.0b7 Email names with UTF-8 characters are now properly encoded [wb, 2009-05-08]
* @changes 1.0.0b6 Fixed a bug where <> quoted email addresses in validation messages were not showing [wb, 2009-03-27]
* @changes 1.0.0b5 Updated for new fCore API [wb, 2009-02-16]
* @changes 1.0.0b4 The recipient error message in ::validate() no longer contains a typo [wb, 2009-02-09]
* @changes 1.0.0b3 Fixed a bug with missing content in the fValidationException thrown by ::validate() [wb, 2009-01-14]
* @changes 1.0.0b2 Fixed a few bugs with sending S/MIME encrypted/signed emails [wb, 2009-01-10]
* @changes 1.0.0b The initial implementation [wb, 2008-06-23]
*/
class fEmail
{
// The following constants allow for nice looking callbacks to static methods
const combineNameEmail = 'fEmail::combineNameEmail';
const fixQmail = 'fEmail::fixQmail';
const getFQDN = 'fEmail::getFQDN';
const reset = 'fEmail::reset';
const unindentExpand = 'fEmail::unindentExpand';
/**
* A regular expression to match an email address, exluding those with comments and folding whitespace
*
* The matches will be:
*
* - `[0]`: The whole email address
* - `[1]`: The name before the `@`
* - `[2]`: The domain/ip after the `@`
*
* @var string
*/
const EMAIL_REGEX = '~^[ \t]*( # Allow leading whitespace
(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+") # An "atom" or a quoted string
(?:\.[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))* # A . plus another "atom" or a quoted string, any number of times
)@( # The @ symbol
(?:[a-z0-9\\-]+\.)+[a-z]{2,}| # Domain name
\[(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5])\] # (or) IP addresses
)[ \t]*$~ixD'; # Allow Trailing whitespace
/**
* A regular expression to match a `name <email>` string, exluding those with comments and folding whitespace
*
* The matches will be:
*
* - `[0]`: The whole name and email address
* - `[1]`: The name
* - `[2]`: The whole email address
* - `[3]`: The email username before the `@`
* - `[4]`: The email domain/ip after the `@`
*
* @var string
*/
const NAME_EMAIL_REGEX = '~^[ \t]*( # Allow leading whitespace
(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+[ \t]*|"[^"\\\\\n\r]+"[ \t]*) # An "atom" or a quoted string
(?:\.?[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+[ \t]*|"[^"\\\\\n\r]+"[ \t]*))*) # Another "atom" or a quoted string or a . followed by one of those, any number of times
[ \t]*<[ \t]*(( # The < encapsulating the email address
(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+") # An "atom" or a quoted string
(?:\.[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))* # A . plus another "atom" or a quoted string, any number of times
)@( # The @ symbol
(?:[a-z0-9\\-]+\.)+[a-z]{2,}| # Domain nam
\[(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5])\] # (or) IP addresses
))[ \t]*>[ \t]*$~ixD'; # Closing > and trailing whitespace
/**
* Flags if the class should convert `\r\n` to `\n` for qmail. This makes invalid email headers that may work.
*
* @var boolean
*/
static private $convert_crlf = FALSE;
/**
* The local fully-qualified domain name
*/
static private $fqdn;
/**
* Flags if the class should use [http://php.net/popen popen()] to send mail via sendmail
*
* @var boolean
*/
static private $popen_sendmail = FALSE;
/**
* Turns a name and email into a `"name" <email>` string, or just `email` if no name is provided
*
* This method will remove newline characters from the name and email, and
* will remove any backslash (`\`) and double quote (`"`) characters from
* the name.
*
* @internal
*
* @param string $name The name associated with the email address
* @param string $email The email address
* @return string The '"name" <email>' or 'email' string
*/
static public function combineNameEmail($name, $email)
{
// Strip lower ascii character since they aren't useful in email addresses
$email = preg_replace('#[\x0-\x19]+#', '', $email);
$name = preg_replace('#[\x0-\x19]+#', '', $name);
if (!$name) {
return $email;
}
// If the name contains any non-ascii bytes or stuff not allowed
// in quoted strings we just make an encoded word out of it
if (preg_replace('#[\x80-\xff\x5C\x22]#', '', $name) != $name) {
// The longest header name that will contain email addresses is
// "Bcc: ", which is 5 characters long
$name = self::makeEncodedWord($name, 5);
} else {
$name = '"' . $name . '"';
}
return $name . ' <' . $email . '>';
}
/**
* Composes text using fText if loaded
*
* @param string $message The message to compose
* @param mixed $component A string or number to insert into the message
* @param mixed ...
* @return string The composed and possible translated message
*/
static protected function compose($message)
{
$args = array_slice(func_get_args(), 1);
if (class_exists('fText', FALSE)) {
return call_user_func_array(
array('fText', 'compose'),
array($message, $args)
);
} else {
return vsprintf($message, $args);
}
}
/**
* Sets the class to try and fix broken qmail implementations that add `\r` to `\r\n`
*
* Before trying to fix qmail with this method, please try using fSMTP
* to connect to `localhost` and pass the fSMTP object to ::send().
*
* @return void
*/
static public function fixQmail()
{
if (fCore::checkOS('windows')) {
return;
}
$sendmail_command = ini_get('sendmail_path');
if (!$sendmail_command) {
self::$convert_crlf = TRUE;
trigger_error(
self::compose('The proper fix for sending through qmail is not possible since the sendmail path is not set'),
E_USER_WARNING
);
trigger_error(
self::compose('Trying to fix qmail by converting all \r\n to \n. This will cause invalid (but possibly functioning) email headers to be generated.'),
E_USER_WARNING
);
}
$sendmail_command_parts = explode(' ', $sendmail_command, 2);
$sendmail_path = $sendmail_command_parts[0];
$sendmail_dir = pathinfo($sendmail_path, PATHINFO_DIRNAME);
$sendmail_params = (isset($sendmail_command_parts[1])) ? $sendmail_command_parts[1] : '';
// Check to see if we can run sendmail via popen
$executable = FALSE;
$safe_mode = FALSE;
if (!in_array(strtolower(ini_get('safe_mode')), array('0', '', 'off'))) {
$safe_mode = TRUE;
$exec_dirs = explode(';', ini_get('safe_mode_exec_dir'));
foreach ($exec_dirs as $exec_dir) {
if (stripos($sendmail_dir, $exec_dir) !== 0) {
continue;
}
if (file_exists($sendmail_path) && is_executable($sendmail_path)) {
$executable = TRUE;
}
}
} else {
if (file_exists($sendmail_path) && is_executable($sendmail_path)) {
$executable = TRUE;
}
}
if ($executable) {
self::$popen_sendmail = TRUE;
} else {
self::$convert_crlf = TRUE;
if ($safe_mode) {
trigger_error(
self::compose('The proper fix for sending through qmail is not possible since safe mode is turned on and the sendmail binary is not in one of the paths defined by the safe_mode_exec_dir ini setting'),
E_USER_WARNING
);
trigger_error(
self::compose('Trying to fix qmail by converting all \r\n to \n. This will cause invalid (but possibly functioning) email headers to be generated.'),
E_USER_WARNING
);
} else {
trigger_error(
self::compose('The proper fix for sending through qmail is not possible since the sendmail binary could not be found or is not executable'),
E_USER_WARNING
);
trigger_error(
self::compose('Trying to fix qmail by converting all \r\n to \n. This will cause invalid (but possibly functioning) email headers to be generated.'),
E_USER_WARNING
);
}
}
}
/**
* Returns the fully-qualified domain name of the server
*
* @internal
*
* @return string The fully-qualified domain name of the server
*/
static public function getFQDN()
{
if (self::$fqdn !== NULL) {
return self::$fqdn;
}
if (isset($_ENV['HOST'])) {
self::$fqdn = $_ENV['HOST'];
}
if (strpos(self::$fqdn, '.') === FALSE && isset($_ENV['HOSTNAME'])) {
self::$fqdn = $_ENV['HOSTNAME'];
}
if (strpos(self::$fqdn, '.') === FALSE) {
self::$fqdn = php_uname('n');
}
if (strpos(self::$fqdn, '.') === FALSE) {
$can_exec = !in_array('exec', array_map('trim', explode(',', ini_get('disable_functions')))) && !ini_get('safe_mode');
if (fCore::checkOS('linux') && $can_exec) {
self::$fqdn = trim(shell_exec('hostname --fqdn'));
} elseif (fCore::checkOS('windows')) {
$shell = new COM('WScript.Shell');
$tcpip_key = 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip';
try {
$domain = $shell->RegRead($tcpip_key . '\Parameters\NV Domain');
} catch (com_exception $e) {
try {
$domain = $shell->RegRead($tcpip_key . '\Parameters\DhcpDomain');
} catch (com_exception $e) {
try {
$adapters = $shell->RegRead($tcpip_key . '\Linkage\Route');
foreach ($adapters as $adapter) {
if ($adapter[0] != '{') { continue; }
try {
$domain = $shell->RegRead($tcpip_key . '\Interfaces\\' . $adapter . '\Domain');
} catch (com_exception $e) {
try {
$domain = $shell->RegRead($tcpip_key . '\Interfaces\\' . $adapter . '\DhcpDomain');
} catch (com_exception $e) { }
}
}
} catch (com_exception $e) { }
}
}
if (!empty($domain)) {
self::$fqdn .= '.' . $domain;
}
} elseif (!fCore::checkOS('windows') && !ini_get('open_basedir') && file_exists('/etc/resolv.conf')) {
$output = file_get_contents('/etc/resolv.conf');
if (preg_match('#^domain ([a-z0-9_.-]+)#im', $output, $match)) {
self::$fqdn .= '.' . $match[1];
}
}
}
return self::$fqdn;
}
/**
* Encodes a string to UTF-8 encoded-word
*
* @param string $content The content to encode
* @param integer $first_line_prefix_length The length of any prefix applied to the first line of the encoded word - this allows properly accounting for a header name
* @return string The encoded string
*/
static private function makeEncodedWord($content, $first_line_prefix_length)
{
// Homogenize the line-endings to CRLF
$content = str_replace("\r\n", "\n", $content);
$content = str_replace("\r", "\n", $content);
$content = str_replace("\n", "\r\n", $content);
// Encoded word is not required if all characters are ascii
if (!preg_match('#[\x80-\xFF]#', $content)) {
return $content;
}
// A quick a dirty hex encoding
$content = rawurlencode($content);
$content = str_replace('=', '%3D', $content);
$content = str_replace('%', '=', $content);
// Decode characters that don't have to be coded
$decodings = array(
'=20' => '_', '=21' => '!', '=22' => '"', '=23' => '#',
'=24' => '$', '=25' => '%', '=26' => '&', '=27' => "'",
'=28' => '(', '=29' => ')', '=2A' => '*', '=2B' => '+',
'=2C' => ',', '=2D' => '-', '=2E' => '.', '=2F' => '/',
'=3A' => ':', '=3B' => ';', '=3C' => '<', '=3E' => '>',
'=40' => '@', '=5B' => '[', '=5C' => '\\', '=5D' => ']',
'=5E' => '^', '=60' => '`', '=7B' => '{', '=7C' => '|',
'=7D' => '}', '=7E' => '~', ' ' => '_'
);
$content = strtr($content, $decodings);
$length = strlen($content);
$prefix = '=?utf-8?Q?';
$suffix = '?=';
$prefix_length = 10;
$suffix_length = 2;
// This loop goes through and ensures we are wrapping by 75 chars
// including the encoded word delimiters
$output = $prefix;
$line_length = $prefix_length + $first_line_prefix_length;
for ($i=0; $i<$length; $i++) {
// Get info about the next character
$char_length = ($content[$i] == '=') ? 3 : 1;
$char = $content[$i];
if ($char_length == 3) {
$char .= $content[$i+1] . $content[$i+2];
}
// If we have too long a line, wrap it
if ($line_length + $suffix_length + $char_length > 75) {
$output .= $suffix . "\r\n " . $prefix;
$line_length = $prefix_length + 2;
}
// Add the character
$output .= $char;
// Figure out how much longer the line is
$line_length += $char_length;
// Skip characters if we have an encoded character
$i += $char_length-1;
}
if (substr($output, -2) != $suffix) {
$output .= $suffix;
}
return $output;
}
/**
* Resets the configuration of the class
*
* @internal
*
* @return void
*/
static public function reset()
{
self::$convert_crlf = FALSE;
self::$fqdn = NULL;
self::$popen_sendmail = FALSE;
}
/**
* Returns `TRUE` for non-empty strings, numbers, objects, empty numbers and string-like numbers (such as `0`, `0.0`, `'0'`)
*
* @param mixed $value The value to check
* @return boolean If the value is string-like
*/
static protected function stringlike($value)
{
if ((!is_string($value) && !is_object($value) && !is_numeric($value)) || !strlen(trim($value))) {
return FALSE;
}
return TRUE;
}
/**
* Takes a block of text, unindents it and replaces {CONSTANT} tokens with the constant's value
*
* @param string $text The text to unindent and replace constants in
* @return string The unindented text
*/
static public function unindentExpand($text)
{
$text = preg_replace('#^[ \t]*\n|\n[ \t]*$#D', '', $text);
if (preg_match('#^[ \t]+(?=\S)#m', $text, $match)) {
$text = preg_replace('#^' . preg_quote($match[0]) . '#m', '', $text);
}
preg_match_all('#\{([a-z][a-z0-9_]*)\}#i', $text, $constants, PREG_SET_ORDER);
foreach ($constants as $constant) {
if (!defined($constant[1])) { continue; }
$text = preg_replace('#' . preg_quote($constant[0], '#') . '#', constant($constant[1]), $text, 1);
}
return $text;
}
/**
* The file contents to attach
*
* @var array
*/
private $attachments = array();
/**
* The email address(es) to BCC to
*
* @var array
*/
private $bcc_emails = array();
/**
* The email address to bounce to
*
* @var string
*/
private $bounce_to_email = NULL;
/**
* The email address(es) to CC to
*
* @var array
*/
private $cc_emails = array();
/**
* Custom headers
*
* @var array
*/
private $custom_headers = array();
/**
* The email address being sent from
*
* @var string
*/
private $from_email = NULL;
/**
* The HTML body of the email
*
* @var string
*/
private $html_body = NULL;
/**
* The Message-ID header for the email
*
* @var string
*/
private $message_id = NULL;
/**
* The plaintext body of the email
*
* @var string
*/
private $plaintext_body = NULL;
/**
* The recipient's S/MIME PEM certificate filename, used for encryption of the message
*
* @var string
*/
private $recipients_smime_cert_file = NULL;
/**
* The files to include as multipart/related
*
* @var array
*/
private $related_files = array();
/**
* The email address to reply to
*
* @var string
*/
private $reply_to_email = NULL;
/**
* The email address actually sending the email
*
* @var string
*/
private $sender_email = NULL;
/**
* The senders's S/MIME PEM certificate filename, used for singing the message
*
* @var string
*/
private $senders_smime_cert_file = NULL;
/**
* The senders's S/MIME private key filename, used for singing the message
*
* @var string
*/
private $senders_smime_pk_file = NULL;
/**
* The senders's S/MIME private key password, used for singing the message
*
* @var string
*/
private $senders_smime_pk_password = NULL;
/**
* If the message should be encrypted using the recipient's S/MIME certificate
*
* @var boolean
*/
private $smime_encrypt = FALSE;
/**
* If the message should be signed using the senders's S/MIME private key
*
* @var boolean
*/
private $smime_sign = FALSE;
/**
* The subject of the email
*
* @var string
*/
private $subject = NULL;
/**
* The email address(es) to send to
*
* @var array
*/
private $to_emails = array();
/**
* Initializes fEmail for creating message ids
*
* @return fEmail
*/
public function __construct()
{
$this->message_id = '<' . fCryptography::randomString(10, 'hexadecimal') . '.' . time() . '@' . self::getFQDN() . '>';
}
/**
* All requests that hit this method should be requests for callbacks
*
* @internal
*
* @param string $method The method to create a callback for
* @return callback The callback for the method requested
*/
public function __get($method)
{
return array($this, $method);
}
/**
* Adds an attachment to the email
*
* If a duplicate filename is detected, it will be changed to be unique.
*
* @param string|fFile $contents The contents of the file
* @param string $filename The name to give the attachement - optional if `$contents` is an fFile object
* @param string $mime_type The mime type of the file - this allows overriding the mime type of the file if incorrectly detected
* @return fEmail The email object, to allow for method chaining
*/
public function addAttachment($contents, $filename=NULL, $mime_type=NULL)
{
$this->extrapolateFileInfo($contents, $filename, $mime_type);
while (isset($this->attachments[$filename])) {
$filename = $this->generateNewFilename($filename);
}
$this->attachments[$filename] = array(
'mime-type' => $mime_type,
'contents' => $contents
);
return $this;
}
/**
* Adds a “related” file to the email, returning the `Content-ID` for use in HTML
*
* The purpose of a related file is to be able to reference it in part of
* the HTML body. Image `src` URLs can reference a related file by starting
* the URL with `cid:` and then inserting the `Content-ID`.
*
* If a duplicate filename is detected, it will be changed to be unique.
*
* @param string|fFile $contents The contents of the file
* @param string $filename The name to give the attachement - optional if `$contents` is an fFile object
* @param string $mime_type The mime type of the file - this allows overriding the mime type of the file if incorrectly detected
* @return string The fully-formed `cid:` URL for use in HTML `src` attributes
*/
public function addRelatedFile($contents, $filename=NULL, $mime_type=NULL)
{
$this->extrapolateFileInfo($contents, $filename, $mime_type);
while (isset($this->related_files[$filename])) {
$filename = $this->generateNewFilename($filename);
}
$cid = count($this->related_files) . '.' . substr($this->message_id, 1, -1);
$this->related_files[$filename] = array(
'mime-type' => $mime_type,
'contents' => $contents,
'content-id' => '<' . $cid . '>'
);
return 'cid:' . $cid;
}
/**
* Adds a blind carbon copy (BCC) email recipient
*
* @param string $email The email address to BCC
* @param string $name The recipient's name
* @return fEmail The email object, to allow for method chaining
*/
public function addBCCRecipient($email, $name=NULL)
{
if (!$email) {
return;
}
$this->bcc_emails[] = self::combineNameEmail($name, $email);
return $this;
}
/**
* Adds a carbon copy (CC) email recipient
*
* @param string $email The email address to BCC
* @param string $name The recipient's name
* @return fEmail The email object, to allow for method chaining
*/
public function addCCRecipient($email, $name=NULL)
{
if (!$email) {
return;
}
$this->cc_emails[] = self::combineNameEmail($name, $email);
return $this;
}
/**
* Allows adding a custom header to the email
*
* If the method is called multiple times with the same name, the last
* value will be used.
*
* Please note that this class will properly format the header, including
* adding the `:` between the name and value and wrapping values that are
* too long for a single line.
*
* @param string $name The name of the header
* @param string $value The value of the header
* @param array :$headers An associative array of `{name} => {value}`
* @return fEmail The email object, to allow for method chaining
*/
public function addCustomHeader($name, $value=NULL)
{
if ($value === NULL && is_array($name)) {
foreach ($name as $key => $value) {
$this->addCustomHeader($key, $value);
}
return;
}
$lower_name = fUTF8::lower($name);
$this->custom_headers[$lower_name] = array($name, $value);
return $this;
}
/**
* Adds an email recipient
*
* @param string $email The email address to send to
* @param string $name The recipient's name
* @return fEmail The email object, to allow for method chaining
*/
public function addRecipient($email, $name=NULL)
{
if (!$email) {
return;
}
$this->to_emails[] = self::combineNameEmail($name, $email);
return $this;
}
/**
* Takes a multi-address email header and builds it out using an array of emails
*
* @param string $header The header name without `': '`, the header is non-blank, `': '` will be added
* @param array $emails The email addresses for the header
* @return string The email header with a trailing `\r\n`
*/
private function buildMultiAddressHeader($header, $emails)
{
$header .= ': ';
$first = TRUE;
$line = 1;
foreach ($emails as $email) {
if ($first) { $first = FALSE; } else { $header .= ', '; }
// Try to stay within the recommended 78 character line limit
$last_crlf_pos = (integer) strrpos($header, "\r\n");
if (strlen($header . $email) - $last_crlf_pos > 78) {
$header .= "\r\n ";
$line++;
}
$header .= trim($email);
}
return $header . "\r\n";
}
/**
* Removes all To, CC and BCC recipients from the email
*
* @return fEmail The email object, to allow for method chaining
*/
public function clearRecipients()
{
$this->to_emails = array();
$this->cc_emails = array();
$this->bcc_emails = array();
return $this;
}
/**
* Creates a 32-character boundary for a multipart message
*
* @return string A multipart boundary
*/
private function createBoundary()
{
$chars = 'ancdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:-_';
$last_index = strlen($chars) - 1;
$output = '';
for ($i = 0; $i < 28; $i++) {
$output .= $chars[rand(0, $last_index)];
}
return $output;
}
/**
* Builds the body of the email
*
* @param string $boundary The boundary to use for the top level mime block
* @return string The message body to be sent to the mail() function
*/
private function createBody($boundary)
{
$boundary_stack = array($boundary);
$mime_notice = self::compose(
"This message has been formatted using MIME. It does not appear that your\r\nemail client supports MIME."
);
$body = '';
if ($this->html_body || $this->attachments) {
$body .= $mime_notice . "\r\n\r\n";
}
if ($this->html_body && $this->related_files && $this->attachments) {
$body .= '--' . end($boundary_stack) . "\r\n";
$boundary_stack[] = $this->createBoundary();
$body .= 'Content-Type: multipart/related; boundary="' . end($boundary_stack) . "\"\r\n\r\n";
}
if ($this->html_body && ($this->attachments || $this->related_files)) {
$body .= '--' . end($boundary_stack) . "\r\n";
$boundary_stack[] = $this->createBoundary();
$body .= 'Content-Type: multipart/alternative; boundary="' . end($boundary_stack) . "\"\r\n\r\n";
}
if ($this->html_body || $this->attachments) {
$body .= '--' . end($boundary_stack) . "\r\n";
$body .= "Content-Type: text/plain; charset=utf-8\r\n";
$body .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
}
$body .= $this->makeQuotedPrintable($this->plaintext_body) . "\r\n";
if ($this->html_body) {
$body .= '--' . end($boundary_stack) . "\r\n";
$body .= "Content-Type: text/html; charset=utf-8\r\n";
$body .= "Content-Transfer-Encoding: quoted-printable\r\n\r\n";
$body .= $this->makeQuotedPrintable($this->html_body) . "\r\n";
}
if ($this->related_files) {
$body .= '--' . end($boundary_stack) . "--\r\n";
array_pop($boundary_stack);
foreach ($this->related_files as $filename => $file_info) {
$body .= '--' . end($boundary_stack) . "\r\n";
$body .= 'Content-Type: ' . $file_info['mime-type'] . '; name="' . $filename . "\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= 'Content-ID: ' . $file_info['content-id'] . "\r\n\r\n";
$body .= $this->makeBase64($file_info['contents']) . "\r\n";
}
}
if ($this->attachments) {
if ($this->html_body) {
$body .= '--' . end($boundary_stack) . "--\r\n";
array_pop($boundary_stack);
}
foreach ($this->attachments as $filename => $file_info) {
$body .= '--' . end($boundary_stack) . "\r\n";
$body .= 'Content-Type: ' . $file_info['mime-type'] . "\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= 'Content-Disposition: attachment; filename="' . $filename . "\";\r\n\r\n";
$body .= $this->makeBase64($file_info['contents']) . "\r\n";
}
}
if ($this->html_body || $this->attachments) {
$body .= '--' . end($boundary_stack) . "--\r\n";
array_pop($boundary_stack);
}
return $body;
}
/**
* Builds the headers for the email
*
* @param string $boundary The boundary to use for the top level mime block
* @param string $message_id The message id for the message
* @return string The headers to be sent to the [http://php.net/function.mail mail()] function
*/
private function createHeaders($boundary, $message_id)
{
$headers = '';
if ($this->cc_emails) {
$headers .= $this->buildMultiAddressHeader("Cc", $this->cc_emails);
}
if ($this->bcc_emails) {
$headers .= $this->buildMultiAddressHeader("Bcc", $this->bcc_emails);
}
$headers .= "From: " . trim($this->from_email) . "\r\n";
if ($this->reply_to_email) {
$headers .= "Reply-To: " . trim($this->reply_to_email) . "\r\n";
}
if ($this->sender_email) {
$headers .= "Sender: " . trim($this->sender_email) . "\r\n";
}
foreach ($this->custom_headers as $header_info) {
$header_prefix = $header_info[0] . ': ';
$headers .= $header_prefix . self::makeEncodedWord($header_info[1], strlen($header_prefix)) . "\r\n";
}
$headers .= "Message-ID: " . $message_id . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
if (!$this->html_body && !$this->attachments) {
$headers .= "Content-Type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\r\n";
} elseif ($this->html_body && !$this->attachments) {
if ($this->related_files) {
$headers .= 'Content-Type: multipart/related; boundary="' . $boundary . "\"\r\n";
} else {
$headers .= 'Content-Type: multipart/alternative; boundary="' . $boundary . "\"\r\n";
}
} elseif ($this->attachments) {
$headers .= 'Content-Type: multipart/mixed; boundary="' . $boundary . "\"\r\n";
}
return $headers . "\r\n";
}
/**
* Takes the body of the message and processes it with S/MIME
*
* @param string $to The recipients being sent to