159.66KiB; PHP | 2020-01-05 19:05:40+01 | SLOC 4271
1
<?php␣
2
/**␣
3
 * PHPMailer - PHP email creation and transport class.␣
4
 * PHP Version 5.5.␣
5
 *␣
6
 * @see       https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project␣
7
 *␣
8
 * @author    Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>␣
9
 * @author    Jim Jagielski (jimjag) <jimjag@gmail.com>␣
10
 * @author    Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>␣
11
 * @author    Brent R. Matzelle (original founder)␣
12
 * @copyright 2012 - 2017 Marcus Bointon␣
13
 * @copyright 2010 - 2012 Jim Jagielski␣
14
 * @copyright 2004 - 2009 Andy Prevost␣
15
 * @license   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License␣
16
 * @note      This program is distributed in the hope that it will be useful - WITHOUT␣
17
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or␣
18
 * FITNESS FOR A PARTICULAR PURPOSE.␣
19
 */␣
20
21
namespace PHPMailer\PHPMailer;␣
22
23
/**␣
24
 * PHPMailer - PHP email creation and transport class.␣
25
 *␣
26
 * @author  Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>␣
27
 * @author  Jim Jagielski (jimjag) <jimjag@gmail.com>␣
28
 * @author  Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>␣
29
 * @author  Brent R. Matzelle (original founder)␣
30
 */␣
31 16
class PHPMailer␣
32
{␣
33
    const CHARSET_ISO88591 = 'iso-8859-1';␣
34
    const CHARSET_UTF8 = 'utf-8';␣
35
36
    const CONTENT_TYPE_PLAINTEXT = 'text/plain';␣
37
    const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';␣
38
    const CONTENT_TYPE_TEXT_HTML = 'text/html';␣
39
    const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';␣
40
    const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';␣
41
    const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';␣
42
43
    const ENCODING_7BIT = '7bit';␣
44
    const ENCODING_8BIT = '8bit';␣
45
    const ENCODING_BASE64 = 'base64';␣
46
    const ENCODING_BINARY = 'binary';␣
47
    const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';␣
48
49
    /**␣
50
     * Email priority.␣
51
     * Options: null (default), 1 = High, 3 = Normal, 5 = low.␣
52
     * When null, the header is not set at all.␣
53
     *␣
54
     * @var int␣
55
     */␣
56
    public $Priority;␣
57
58
    /**␣
59
     * The character set of the message.␣
60
     *␣
61
     * @var string␣
62
     */␣
63
    public $CharSet = self::CHARSET_ISO88591;␣
64
65
    /**␣
66
     * The MIME Content-type of the message.␣
67
     *␣
68
     * @var string␣
69
     */␣
70
    public $ContentType = self::CONTENT_TYPE_PLAINTEXT;␣
71
72
    /**␣
73
     * The message encoding.␣
74
     * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".␣
75
     *␣
76
     * @var string␣
77
     */␣
78
    public $Encoding = self::ENCODING_8BIT;␣
79
80
    /**␣
81
     * Holds the most recent mailer error message.␣
82
     *␣
83
     * @var string␣
84
     */␣
85
    public $ErrorInfo = '';␣
86
87
    /**␣
88
     * The From email address for the message.␣
89
     *␣
90
     * @var string␣
91
     */␣
92
    public $From = 'root@localhost';␣
93
94
    /**␣
95
     * The From name of the message.␣
96
     *␣
97
     * @var string␣
98
     */␣
99
    public $FromName = 'Root User';␣
100
101
    /**␣
102
     * The envelope sender of the message.␣
103
     * This will usually be turned into a Return-Path header by the receiver,␣
104
     * and is the address that bounces will be sent to.␣
105
     * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.␣
106
     *␣
107
     * @var string␣
108
     */␣
109
    public $Sender = '';␣
110
111
    /**␣
112
     * The Subject of the message.␣
113
     *␣
114
     * @var string␣
115
     */␣
116
    public $Subject = '';␣
117
118
    /**␣
119
     * An HTML or plain text message body.␣
120
     * If HTML then call isHTML(true).␣
121
     *␣
122
     * @var string␣
123
     */␣
124
    public $Body = '';␣
125
126
    /**␣
127
     * The plain-text message body.␣
128
     * This body can be read by mail clients that do not have HTML email␣
129
     * capability such as mutt & Eudora.␣
130
     * Clients that can read HTML will view the normal Body.␣
131
     *␣
132
     * @var string␣
133
     */␣
134
    public $AltBody = '';␣
135
136
    /**␣
137
     * An iCal message part body.␣
138
     * Only supported in simple alt or alt_inline message types␣
139
     * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.␣
140
     *␣
141
     * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/␣
142
     * @see http://kigkonsult.se/iCalcreator/␣
143
     *␣
144
     * @var string␣
145
     */␣
146
    public $Ical = '';␣
147
148
    /**␣
149
     * The complete compiled MIME message body.␣
150
     *␣
151
     * @var string␣
152
     */␣
153
    protected $MIMEBody = '';␣
154
155
    /**␣
156
     * The complete compiled MIME message headers.␣
157
     *␣
158
     * @var string␣
159
     */␣
160
    protected $MIMEHeader = '';␣
161
162
    /**␣
163
     * Extra headers that createHeader() doesn't fold in.␣
164
     *␣
165
     * @var string␣
166
     */␣
167
    protected $mailHeader = '';␣
168
169
    /**␣
170
     * Word-wrap the message body to this number of chars.␣
171
     * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.␣
172
     *␣
173
     * @see static::STD_LINE_LENGTH␣
174
     *␣
175
     * @var int␣
176
     */␣
177
    public $WordWrap = 0;␣
178
179
    /**␣
180
     * Which method to use to send mail.␣
181
     * Options: "mail", "sendmail", or "smtp".␣
182
     *␣
183
     * @var string␣
184
     */␣
185
    public $Mailer = 'mail';␣
186
187
    /**␣
188
     * The path to the sendmail program.␣
189
     *␣
190
     * @var string␣
191
     */␣
192
    public $Sendmail = '/usr/sbin/sendmail';␣
193
194
    /**␣
195
     * Whether mail() uses a fully sendmail-compatible MTA.␣
196
     * One which supports sendmail's "-oi -f" options.␣
197
     *␣
198
     * @var bool␣
199
     */␣
200
    public $UseSendmailOptions = true;␣
201
202
    /**␣
203
     * The email address that a reading confirmation should be sent to, also known as read receipt.␣
204
     *␣
205
     * @var string␣
206
     */␣
207
    public $ConfirmReadingTo = '';␣
208
209
    /**␣
210
     * The hostname to use in the Message-ID header and as default HELO string.␣
211
     * If empty, PHPMailer attempts to find one with, in order,␣
212
     * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value␣
213
     * 'localhost.localdomain'.␣
214
     *␣
215
     * @var string␣
216
     */␣
217
    public $Hostname = '';␣
218
219
    /**␣
220
     * An ID to be used in the Message-ID header.␣
221
     * If empty, a unique id will be generated.␣
222
     * You can set your own, but it must be in the format "<id@domain>",␣
223
     * as defined in RFC5322 section 3.6.4 or it will be ignored.␣
224
     *␣
225
     * @see https://tools.ietf.org/html/rfc5322#section-3.6.4␣
226
     *␣
227
     * @var string␣
228
     */␣
229
    public $MessageID = '';␣
230
231
    /**␣
232
     * The message Date to be used in the Date header.␣
233
     * If empty, the current date will be added.␣
234
     *␣
235
     * @var string␣
236
     */␣
237
    public $MessageDate = '';␣
238
239
    /**␣
240
     * SMTP hosts.␣
241
     * Either a single hostname or multiple semicolon-delimited hostnames.␣
242
     * You can also specify a different port␣
243
     * for each host by using this format: [hostname:port]␣
244
     * (e.g. "smtp1.example.com:25;smtp2.example.com").␣
245
     * You can also specify encryption type, for example:␣
246
     * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").␣
247
     * Hosts will be tried in order.␣
248
     *␣
249
     * @var string␣
250
     */␣
251
    public $Host = 'localhost';␣
252
253
    /**␣
254
     * The default SMTP server port.␣
255
     *␣
256
     * @var int␣
257
     */␣
258
    public $Port = 25;␣
259
260
    /**␣
261
     * The SMTP HELO of the message.␣
262
     * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find␣
263
     * one with the same method described above for $Hostname.␣
264
     *␣
265
     * @see PHPMailer::$Hostname␣
266
     *␣
267
     * @var string␣
268
     */␣
269
    public $Helo = '';␣
270
271
    /**␣
272
     * What kind of encryption to use on the SMTP connection.␣
273
     * Options: '', 'ssl' or 'tls'.␣
274
     *␣
275
     * @var string␣
276
     */␣
277
    public $SMTPSecure = '';␣
278
279
    /**␣
280
     * Whether to enable TLS encryption automatically if a server supports it,␣
281
     * even if `SMTPSecure` is not set to 'tls'.␣
282
     * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.␣
283
     *␣
284
     * @var bool␣
285
     */␣
286
    public $SMTPAutoTLS = true;␣
287
288
    /**␣
289
     * Whether to use SMTP authentication.␣
290
     * Uses the Username and Password properties.␣
291
     *␣
292
     * @see PHPMailer::$Username␣
293
     * @see PHPMailer::$Password␣
294
     *␣
295
     * @var bool␣
296
     */␣
297
    public $SMTPAuth = false;␣
298
299
    /**␣
300
     * Options array passed to stream_context_create when connecting via SMTP.␣
301
     *␣
302
     * @var array␣
303
     */␣
304
    public $SMTPOptions = [];␣
305
306
    /**␣
307
     * SMTP username.␣
308
     *␣
309
     * @var string␣
310
     */␣
311
    public $Username = '';␣
312
313
    /**␣
314
     * SMTP password.␣
315
     *␣
316
     * @var string␣
317
     */␣
318
    public $Password = '';␣
319
320
    /**␣
321
     * SMTP auth type.␣
322
     * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.␣
323
     *␣
324
     * @var string␣
325
     */␣
326
    public $AuthType = '';␣
327
328
    /**␣
329
     * An instance of the PHPMailer OAuth class.␣
330
     *␣
331
     * @var OAuth␣
332
     */␣
333
    protected $oauth;␣
334
335
    /**␣
336
     * The SMTP server timeout in seconds.␣
337
     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.␣
338
     *␣
339
     * @var int␣
340
     */␣
341
    public $Timeout = 300;␣
342
343
    /**␣
344
     * Comma separated list of DSN notifications␣
345
     * 'NEVER' under no circumstances a DSN must be returned to the sender.␣
346
     *         If you use NEVER all other notifications will be ignored.␣
347
     * 'SUCCESS' will notify you when your mail has arrived at its destination.␣
348
     * 'FAILURE' will arrive if an error occurred during delivery.␣
349
     * 'DELAY'   will notify you if there is an unusual delay in delivery, but the actual␣
350
     *           delivery's outcome (success or failure) is not yet decided.␣
351
     *␣
352
     * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY␣
353
     */␣
354
    public $dsn = '';␣
355
356
    /**␣
357
     * SMTP class debug output mode.␣
358
     * Debug output level.␣
359
     * Options:␣
360
     * * `0` No output␣
361
     * * `1` Commands␣
362
     * * `2` Data and commands␣
363
     * * `3` As 2 plus connection status␣
364
     * * `4` Low-level data output.␣
365
     *␣
366
     * @see SMTP::$do_debug␣
367
     *␣
368
     * @var int␣
369
     */␣
370
    public $SMTPDebug = 0;␣
371
372
    /**␣
373
     * How to handle debug output.␣
374
     * Options:␣
375
     * * `echo` Output plain-text as-is, appropriate for CLI␣
376
     * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output␣
377
     * * `error_log` Output to error log as configured in php.ini␣
378
     * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.␣
379
     * Alternatively, you can provide a callable expecting two params: a message string and the debug level:␣
380
     *␣
381
     * ```php␣
382
     * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};␣
383
     * ```␣
384
     *␣
385
     * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`␣
386
     * level output is used:␣
387
     *␣
388
     * ```php␣
389
     * $mail->Debugoutput = new myPsr3Logger;␣
390
     * ```␣
391
     *␣
392
     * @see SMTP::$Debugoutput␣
393
     *␣
394
     * @var string|callable|\Psr\Log\LoggerInterface␣
395
     */␣
396
    public $Debugoutput = 'echo';␣
397
398
    /**␣
399
     * Whether to keep SMTP connection open after each message.␣
400
     * If this is set to true then to close the connection␣
401
     * requires an explicit call to smtpClose().␣
402
     *␣
403
     * @var bool␣
404
     */␣
405
    public $SMTPKeepAlive = false;␣
406
407
    /**␣
408
     * Whether to split multiple to addresses into multiple messages␣
409
     * or send them all in one message.␣
410
     * Only supported in `mail` and `sendmail` transports, not in SMTP.␣
411
     *␣
412
     * @var bool␣
413
     */␣
414
    public $SingleTo = false;␣
415
416
    /**␣
417
     * Storage for addresses when SingleTo is enabled.␣
418
     *␣
419
     * @var array␣
420
     */␣
421
    protected $SingleToArray = [];␣
422
423
    /**␣
424
     * Whether to generate VERP addresses on send.␣
425
     * Only applicable when sending via SMTP.␣
426
     *␣
427
     * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path␣
428
     * @see http://www.postfix.org/VERP_README.html Postfix VERP info␣
429
     *␣
430
     * @var bool␣
431
     */␣
432
    public $do_verp = false;␣
433
434
    /**␣
435
     * Whether to allow sending messages with an empty body.␣
436
     *␣
437
     * @var bool␣
438
     */␣
439
    public $AllowEmpty = false;␣
440
441
    /**␣
442
     * DKIM selector.␣
443
     *␣
444
     * @var string␣
445
     */␣
446
    public $DKIM_selector = '';␣
447
448
    /**␣
449
     * DKIM Identity.␣
450
     * Usually the email address used as the source of the email.␣
451
     *␣
452
     * @var string␣
453
     */␣
454
    public $DKIM_identity = '';␣
455
456
    /**␣
457
     * DKIM passphrase.␣
458
     * Used if your key is encrypted.␣
459
     *␣
460
     * @var string␣
461
     */␣
462
    public $DKIM_passphrase = '';␣
463
464
    /**␣
465
     * DKIM signing domain name.␣
466
     *␣
467
     * @example 'example.com'␣
468
     *␣
469
     * @var string␣
470
     */␣
471
    public $DKIM_domain = '';␣
472
473
    /**␣
474
     * DKIM Copy header field values for diagnostic use.␣
475
     *␣
476
     * @var bool␣
477
     */␣
478 1
    public $DKIM_copyHeaderFields = true;␣
479
480
    /**␣
481
     * DKIM Extra signing headers.␣
482
     *␣
483
     * @example ['List-Unsubscribe', 'List-Help']␣
484
     *␣
485
     * @var array␣
486
     */␣
487
    public $DKIM_extraHeaders = [];␣
488
489
    /**␣
490
     * DKIM private key file path.␣
491
     *␣
492
     * @var string␣
493
     */␣
494
    public $DKIM_private = '';␣
495
496
    /**␣
497
     * DKIM private key string.␣
498
     *␣
499
     * If set, takes precedence over `$DKIM_private`.␣
500
     *␣
501
     * @var string␣
502
     */␣
503
    public $DKIM_private_string = '';␣
504
505
    /**␣
506
     * Callback Action function name.␣
507
     *␣
508
     * The function that handles the result of the send email action.␣
509
     * It is called out by send() for each email sent.␣
510
     *␣
511
     * Value can be any php callable: http://www.php.net/is_callable␣
512
     *␣
513
     * Parameters:␣
514
     *   bool $result        result of the send action␣
515
     *   array   $to            email addresses of the recipients␣
516
     *   array   $cc            cc email addresses␣
517
     *   array   $bcc           bcc email addresses␣
518
     *   string  $subject       the subject␣
519
     *   string  $body          the email body␣
520
     *   string  $from          email address of sender␣
521
     *   string  $extra         extra information of possible use␣
522
     *                          "smtp_transaction_id' => last smtp transaction id␣
523
     *␣
524
     * @var string␣
525
     */␣
526
    public $action_function = '';␣
527
528
    /**␣
529
     * What to put in the X-Mailer header.␣
530
     * Options: An empty string for PHPMailer default, whitespace for none, or a string to use.␣
531
     *␣
532
     * @var string␣
533
     */␣
534
    public $XMailer = '';␣
535
536
    /**␣
537
     * Which validator to use by default when validating email addresses.␣
538
     * May be a callable to inject your own validator, but there are several built-in validators.␣
539
     * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.␣
540
     *␣
541
     * @see PHPMailer::validateAddress()␣
542
     *␣
543
     * @var string|callable␣
544
     */␣
545
    public static $validator = 'php';␣
546
547
    /**␣
548
     * An instance of the SMTP sender class.␣
549
     *␣
550
     * @var SMTP␣
551
     */␣
552
    protected $smtp;␣
553
554
    /**␣
555
     * The array of 'to' names and addresses.␣
556
     *␣
557
     * @var array␣
558
     */␣
559 1
    protected $to = [];␣
560
561
    /**␣
562
     * The array of 'cc' names and addresses.␣
563
     *␣
564
     * @var array␣
565
     */␣
566 1
    protected $cc = [];␣
567
568
    /**␣
569
     * The array of 'bcc' names and addresses.␣
570
     *␣
571
     * @var array␣
572
     */␣
573
    protected $bcc = [];␣
574
575
    /**␣
576
     * The array of reply-to names and addresses.␣
577
     *␣
578
     * @var array␣
579
     */␣
580
    protected $ReplyTo = [];␣
581
582
    /**␣
583
     * An array of all kinds of addresses.␣
584
     * Includes all of $to, $cc, $bcc.␣
585
     *␣
586
     * @see PHPMailer::$to␣
587
     * @see PHPMailer::$cc␣
588
     * @see PHPMailer::$bcc␣
589
     *␣
590
     * @var array␣
591
     */␣
592
    protected $all_recipients = [];␣
593
594
    /**␣
595
     * An array of names and addresses queued for validation.␣
596
     * In send(), valid and non duplicate entries are moved to $all_recipients␣
597
     * and one of $to, $cc, or $bcc.␣
598
     * This array is used only for addresses with IDN.␣
599
     *␣
600
     * @see PHPMailer::$to␣
601
     * @see PHPMailer::$cc␣
602
     * @see PHPMailer::$bcc␣
603
     * @see PHPMailer::$all_recipients␣
604
     *␣
605
     * @var array␣
606
     */␣
607
    protected $RecipientsQueue = [];␣
608
609
    /**␣
610
     * An array of reply-to names and addresses queued for validation.␣
611
     * In send(), valid and non duplicate entries are moved to $ReplyTo.␣
612
     * This array is used only for addresses with IDN.␣
613
     *␣
614
     * @see PHPMailer::$ReplyTo␣
615
     *␣
616
     * @var array␣
617
     */␣
618
    protected $ReplyToQueue = [];␣
619
620
    /**␣
621
     * The array of attachments.␣
622
     *␣
623
     * @var array␣
624
     */␣
625
    protected $attachment = [];␣
626
627
    /**␣
628
     * The array of custom headers.␣
629
     *␣
630
     * @var array␣
631
     */␣
632
    protected $CustomHeader = [];␣
633
634
    /**␣
635
     * The most recent Message-ID (including angular brackets).␣
636
     *␣
637
     * @var string␣
638
     */␣
639
    protected $lastMessageID = '';␣
640
641
    /**␣
642
     * The message's MIME type.␣
643
     *␣
644
     * @var string␣
645
     */␣
646
    protected $message_type = '';␣
647
648
    /**␣
649
     * The array of MIME boundary strings.␣
650
     *␣
651
     * @var array␣
652
     */␣
653
    protected $boundary = [];␣
654
655
    /**␣
656
     * The array of available languages.␣
657
     *␣
658
     * @var array␣
659
     */␣
660
    protected $language = [];␣
661
662
    /**␣
663
     * The number of errors encountered.␣
664
     *␣
665
     * @var int␣
666
     */␣
667
    protected $error_count = 0;␣
668
669
    /**␣
670
     * The S/MIME certificate file path.␣
671
     *␣
672
     * @var string␣
673
     */␣
674
    protected $sign_cert_file = '';␣
675
676
    /**␣
677
     * The S/MIME key file path.␣
678
     *␣
679
     * @var string␣
680
     */␣
681
    protected $sign_key_file = '';␣
682
683
    /**␣
684
     * The optional S/MIME extra certificates ("CA Chain") file path.␣
685
     *␣
686
     * @var string␣
687
     */␣
688
    protected $sign_extracerts_file = '';␣
689
690
    /**␣
691
     * The S/MIME password for the key.␣
692
     * Used only if the key is encrypted.␣
693
     *␣
694
     * @var string␣
695
     */␣
696
    protected $sign_key_pass = '';␣
697
698
    /**␣
699
     * Whether to throw exceptions for errors.␣
700
     *␣
701
     * @var bool␣
702
     */␣
703
    protected $exceptions = false;␣
704
705
    /**␣
706
     * Unique ID used for message ID and boundaries.␣
707
     *␣
708
     * @var string␣
709
     */␣
710
    protected $uniqueid = '';␣
711
712
    /**␣
713
     * The PHPMailer Version number.␣
714
     *␣
715
     * @var string␣
716
     */␣
717
    const VERSION = '6.0.7';␣
718
719
    /**␣
720
     * Error severity: message only, continue processing.␣
721
     *␣
722
     * @var int␣
723
     */␣
724
    const STOP_MESSAGE = 0;␣
725
726
    /**␣
727
     * Error severity: message, likely ok to continue processing.␣
728
     *␣
729
     * @var int␣
730
     */␣
731
    const STOP_CONTINUE = 1;␣
732
733
    /**␣
734
     * Error severity: message, plus full stop, critical error reached.␣
735
     *␣
736
     * @var int␣
737
     */␣
738
    const STOP_CRITICAL = 2;␣
739
740
    /**␣
741
     * SMTP RFC standard line ending.␣
742
     *␣
743
     * @var string␣
744
     */␣
745 1
    protected static $LE = "\r\n";␣
746
747
    /**␣
748
     * The maximum line length allowed by RFC 2822 section 2.1.1.␣
749
     *␣
750
     * @var int␣
751
     */␣
752
    const MAX_LINE_LENGTH = 998;␣
753
754
    /**␣
755
     * The lower maximum line length allowed by RFC 2822 section 2.1.1.␣
756
     * This length does NOT include the line break␣
757
     * 76 means that lines will be 77 or 78 chars depending on whether␣
758
     * the line break format is LF or CRLF; both are valid.␣
759
     *␣
760
     * @var int␣
761
     */␣
762
    const STD_LINE_LENGTH = 76;␣
763
764
    /**␣
765
     * Constructor.␣
766
     *␣
767
     * @param bool $exceptions Should we throw external exceptions?␣
768
     */␣
769
    public function __construct($exceptions = null)␣
770
    {␣
771
        if (null !== $exceptions) {␣
772
            $this->exceptions = (bool) $exceptions;␣
773
        }␣
774
        //Pick an appropriate debug output format automatically␣
775
        $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');␣
776
    }␣
777
778
    /**␣
779
     * Destructor.␣
780
     */␣
781
    public function __destruct()␣
782
    {␣
783
        //Close any open SMTP connection nicely␣
784
        $this->smtpClose();␣
785
    }␣
786
787
    /**␣
788
     * Call mail() in a safe_mode-aware fashion.␣
789
     * Also, unless sendmail_path points to sendmail (or something that␣
790
     * claims to be sendmail), don't pass params (not a perfect fix,␣
791
     * but it will do).␣
792
     *␣
793
     * @param string      $to      To␣
794
     * @param string      $subject Subject␣
795
     * @param string      $body    Message Body␣
796
     * @param string      $header  Additional Header(s)␣
797
     * @param string|null $params  Params␣
798
     *␣
799
     * @return bool␣
800
     */␣
801 1
    private function mailPassthru($to, $subject, $body, $header, $params)␣
802
    {␣
803
        //Check overloading of mail function to avoid double-encoding␣
804
        if (ini_get('mbstring.func_overload') & 1) {␣
805
            $subject = $this->secureHeader($subject);␣
806 1
        } else {␣
807
            $subject = $this->encodeHeader($this->secureHeader($subject));␣
808
        }␣
809
        //Calling mail() with null params breaks␣
810
        if (!$this->UseSendmailOptions or null === $params) {␣
811
            $result = @mail($to, $subject, $body, $header);␣
812 1
        } else {␣
813
            $result = @mail($to, $subject, $body, $header, $params);␣
814
        }␣
815
816
        return $result;␣
817
    }␣
818
819
    /**␣
820
     * Output debugging info via user-defined method.␣
821
     * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).␣
822
     *␣
823
     * @see PHPMailer::$Debugoutput␣
824
     * @see PHPMailer::$SMTPDebug␣
825
     *␣
826
     * @param string $str␣
827
     */␣
828
    protected function edebug($str)␣
829
    {␣
830
        if ($this->SMTPDebug <= 0) {␣
831
            return;␣
832
        }␣
833
        //Is this a PSR-3 logger?␣
834
        if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {␣
835
            $this->Debugoutput->debug($str);␣
836
837
            return;␣
838
        }␣
839
        //Avoid clash with built-in function names␣
840
        if (!in_array($this->Debugoutput, ['error_log', 'html', 'echo']) and is_callable($this->Debugoutput)) {␣
841
            call_user_func($this->Debugoutput, $str, $this->SMTPDebug);␣
842
843
            return;␣
844
        }␣
845
        switch ($this->Debugoutput) {␣
846
            case 'error_log':␣
847
                //Don't output, just log␣
848
                error_log($str);␣
849
                break;␣
850
            case 'html':␣
851
                //Cleans up output a bit for a better looking, HTML-safe output␣
852
                echo htmlentities(␣
853
                    preg_replace('/[\r\n]+/', '', $str),␣
854
                    ENT_QUOTES,␣
855
                    'UTF-8'␣
856
                ), "<br>\n";␣
857
                break;␣
858
            case 'echo':␣
859
            default:␣
860
                //Normalize line breaks␣
861
                $str = preg_replace('/\r\n|\r/ms', "\n", $str);␣
862
                echo gmdate('Y-m-d H:i:s'),␣
863
                "\t",␣
864
                    //Trim trailing space␣
865
                trim(␣
866
                //Indent for readability, except for trailing break␣
867
                    str_replace(␣
868
                        "\n",␣
869
                        "\n                   \t                  ",␣
870
                        trim($str)␣
871
                    )␣
872
                ),␣
873
                "\n";␣
874
        }␣
875
    }␣
876
877
    /**␣
878
     * Sets message type to HTML or plain.␣
879
     *␣
880
     * @param bool $isHtml True for HTML mode␣
881
     */␣
882 1
    public function isHTML($isHtml = true)␣
883
    {␣
884
        if ($isHtml) {␣
885
            $this->ContentType = static::CONTENT_TYPE_TEXT_HTML;␣
886 1
        } else {␣
887
            $this->ContentType = static::CONTENT_TYPE_PLAINTEXT;␣
888
        }␣
889
    }␣
890
891
    /**␣
892
     * Send messages using SMTP.␣
893
     */␣
894
    public function isSMTP()␣
895
    {␣
896
        $this->Mailer = 'smtp';␣
897
    }␣
898
899
    /**␣
900
     * Send messages using PHP's mail() function.␣
901
     */␣
902
    public function isMail()␣
903
    {␣
904
        $this->Mailer = 'mail';␣
905
    }␣
906
907
    /**␣
908
     * Send messages using $Sendmail.␣
909
     */␣
910 3
    public function isSendmail()␣
911
    {␣
912
        $ini_sendmail_path = ini_get('sendmail_path');␣
913
914
        if (false === stripos($ini_sendmail_path, 'sendmail')) {␣
915
            $this->Sendmail = '/usr/sbin/sendmail';␣
916 1
        } else {␣
917
            $this->Sendmail = $ini_sendmail_path;␣
918
        }␣
919
        $this->Mailer = 'sendmail';␣
920
    }␣
921
922
    /**␣
923
     * Send messages using qmail.␣
924
     */␣
925 3
    public function isQmail()␣
926
    {␣
927
        $ini_sendmail_path = ini_get('sendmail_path');␣
928
929
        if (false === stripos($ini_sendmail_path, 'qmail')) {␣
930
            $this->Sendmail = '/var/qmail/bin/qmail-inject';␣
931 1
        } else {␣
932
            $this->Sendmail = $ini_sendmail_path;␣
933
        }␣
934
        $this->Mailer = 'qmail';␣
935
    }␣
936
937
    /**␣
938
     * Add a "To" address.␣
939
     *␣
940
     * @param string $address The email address to send to␣
941
     * @param string $name␣
942
     *␣
943
     * @throws Exception␣
944
     *␣
945
     * @return bool true on success, false if address already used or invalid in some way␣
946
     */␣
947
    public function addAddress($address, $name = '')␣
948
    {␣
949
        return $this->addOrEnqueueAnAddress('to', $address, $name);␣
950
    }␣
951
952
    /**␣
953
     * Add a "CC" address.␣
954
     *␣
955
     * @param string $address The email address to send to␣
956
     * @param string $name␣
957
     *␣
958
     * @throws Exception␣
959
     *␣
960
     * @return bool true on success, false if address already used or invalid in some way␣
961
     */␣
962
    public function addCC($address, $name = '')␣
963
    {␣
964
        return $this->addOrEnqueueAnAddress('cc', $address, $name);␣
965
    }␣
966
967
    /**␣
968
     * Add a "BCC" address.␣
969
     *␣
970
     * @param string $address The email address to send to␣
971
     * @param string $name␣
972
     *␣
973
     * @throws Exception␣
974
     *␣
975
     * @return bool true on success, false if address already used or invalid in some way␣
976
     */␣
977
    public function addBCC($address, $name = '')␣
978
    {␣
979
        return $this->addOrEnqueueAnAddress('bcc', $address, $name);␣
980
    }␣
981
982
    /**␣
983
     * Add a "Reply-To" address.␣
984
     *␣
985
     * @param string $address The email address to reply to␣
986
     * @param string $name␣
987
     *␣
988
     * @throws Exception␣
989
     *␣
990
     * @return bool true on success, false if address already used or invalid in some way␣
991
     */␣
992
    public function addReplyTo($address, $name = '')␣
993
    {␣
994
        return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);␣
995
    }␣
996
997
    /**␣
998
     * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer␣
999
     * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still␣
1000
     * be modified after calling this function), addition of such addresses is delayed until send().␣
1001
     * Addresses that have been added already return false, but do not throw exceptions.␣
1002
     *␣
1003
     * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'␣
1004
     * @param string $address The email address to send, resp. to reply to␣
1005
     * @param string $name␣
1006
     *␣
1007
     * @throws Exception␣
1008
     *␣
1009
     * @return bool true on success, false if address already used or invalid in some way␣
1010
     */␣
1011 4
    protected function addOrEnqueueAnAddress($kind, $address, $name)␣
1012
    {␣
1013
        $address = trim($address);␣
1014
        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim␣
1015
        $pos = strrpos($address, '@');␣
1016
        if (false === $pos) {␣
1017
            // At-sign is missing.␣
1018
            $error_message = sprintf(␣
1019
                '%s (%s): %s',␣
1020
                $this->lang('invalid_address'),␣
1021
                $kind,␣
1022
                $address␣
1023
            );␣
1024
            $this->setError($error_message);␣
1025
            $this->edebug($error_message);␣
1026
            if ($this->exceptions) {␣
1027
                throw new Exception($error_message);␣
1028
            }␣
1029
1030
            return false;␣
1031
        }␣
1032
        $params = [$kind, $address, $name];␣
1033
        // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.␣
1034
        if ($this->has8bitChars(substr($address, ++$pos)) and static::idnSupported()) {␣
1035
            if ('Reply-To' != $kind) {␣
1036
                if (!array_key_exists($address, $this->RecipientsQueue)) {␣
1037
                    $this->RecipientsQueue[$address] = $params;␣
1038
1039
                    return true;␣
1040
                }␣
1041 1
            } else {␣
1042
                if (!array_key_exists($address, $this->ReplyToQueue)) {␣
1043
                    $this->ReplyToQueue[$address] = $params;␣
1044
1045
                    return true;␣
1046
                }␣
1047
            }␣
1048
1049
            return false;␣
1050
        }␣
1051
1052
        // Immediately add standard addresses without IDN.␣
1053
        return call_user_func_array([$this, 'addAnAddress'], $params);␣
1054
    }␣
1055
1056
    /**␣
1057
     * Add an address to one of the recipient arrays or to the ReplyTo array.␣
1058
     * Addresses that have been added already return false, but do not throw exceptions.␣
1059
     *␣
1060
     * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'␣
1061
     * @param string $address The email address to send, resp. to reply to␣
1062
     * @param string $name␣
1063
     *␣
1064
     * @throws Exception␣
1065
     *␣
1066
     * @return bool true on success, false if address already used or invalid in some way␣
1067
     */␣
1068
    protected function addAnAddress($kind, $address, $name = '')␣
1069
    {␣
1070
        if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {␣
1071
            $error_message = sprintf('%s: %s',␣
1072
                $this->lang('Invalid recipient kind'),␣
1073
                $kind);␣
1074
            $this->setError($error_message);␣
1075
            $this->edebug($error_message);␣
1076
            if ($this->exceptions) {␣
1077
                throw new Exception($error_message);␣
1078
            }␣
1079
1080
            return false;␣
1081
        }␣
1082
        if (!static::validateAddress($address)) {␣
1083
            $error_message = sprintf('%s (%s): %s',␣
1084
                $this->lang('invalid_address'),␣
1085
                $kind,␣
1086
                $address);␣
1087
            $this->setError($error_message);␣
1088
            $this->edebug($error_message);␣
1089
            if ($this->exceptions) {␣
1090
                throw new Exception($error_message);␣
1091
            }␣
1092
1093
            return false;␣
1094
        }␣
1095
        if ('Reply-To' != $kind) {␣
1096
            if (!array_key_exists(strtolower($address), $this->all_recipients)) {␣
1097
                $this->{$kind}[] = [$address, $name];␣
1098
                $this->all_recipients[strtolower($address)] = true;␣
1099
1100
                return true;␣
1101
            }␣
1102 1
        } else {␣
1103
            if (!array_key_exists(strtolower($address), $this->ReplyTo)) {␣
1104
                $this->ReplyTo[strtolower($address)] = [$address, $name];␣
1105
1106
                return true;␣
1107
            }␣
1108
        }␣
1109
1110
        return false;␣
1111
    }␣
1112
1113
    /**␣
1114
     * Parse and validate a string containing one or more RFC822-style comma-separated email addresses␣
1115
     * of the form "display name <address>" into an array of name/address pairs.␣
1116
     * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.␣
1117
     * Note that quotes in the name part are removed.␣
1118
     *␣
1119
     * @see    http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation␣
1120
     *␣
1121
     * @param string $addrstr The address list string␣
1122
     * @param bool   $useimap Whether to use the IMAP extension to parse the list␣
1123
     *␣
1124
     * @return array␣
1125
     */␣
1126 2
    public static function parseAddresses($addrstr, $useimap = true)␣
1127
    {␣
1128
        $addresses = [];␣
1129
        if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {␣
1130
            //Use this built-in parser if it's available␣
1131
            $list = imap_rfc822_parse_adrlist($addrstr, '');␣
1132
            foreach ($list as $address) {␣
1133
                if ('.SYNTAX-ERROR.' != $address->host) {␣
1134
                    if (static::validateAddress($address->mailbox . '@' . $address->host)) {␣
1135
                        $addresses[] = [␣
1136
                            'name' => (property_exists($address, 'personal') ? $address->personal : ''),␣
1137
                            'address' => $address->mailbox . '@' . $address->host,␣
1138
                        ];␣
1139
                    }␣
1140
                }␣
1141
            }␣
1142 1
        } else {␣
1143
            //Use this simpler parser␣
1144
            $list = explode(',', $addrstr);␣
1145
            foreach ($list as $address) {␣
1146
                $address = trim($address);␣
1147
                //Is there a separate name part?␣
1148
                if (strpos($address, '<') === false) {␣
1149
                    //No separate name, just use the whole thing␣
1150
                    if (static::validateAddress($address)) {␣
1151
                        $addresses[] = [␣
1152
                            'name' => '',␣
1153
                            'address' => $address,␣
1154
                        ];␣
1155
                    }␣
1156 1
                } else {␣
1157
                    list($name, $email) = explode('<', $address);␣
1158
                    $email = trim(str_replace('>', '', $email));␣
1159
                    if (static::validateAddress($email)) {␣
1160
                        $addresses[] = [␣
1161 1
                            'name' => trim(str_replace(['"', "'"], '', $name)),␣
1162
                            'address' => $email,␣
1163
                        ];␣
1164
                    }␣
1165
                }␣
1166
            }␣
1167
        }␣
1168
1169
        return $addresses;␣
1170
    }␣
1171
1172
    /**␣
1173
     * Set the From and FromName properties.␣
1174
     *␣
1175
     * @param string $address␣
1176
     * @param string $name␣
1177
     * @param bool   $auto    Whether to also set the Sender address, defaults to true␣
1178
     *␣
1179
     * @throws Exception␣
1180
     *␣
1181
     * @return bool␣
1182
     */␣
1183 1
    public function setFrom($address, $name = '', $auto = true)␣
1184
    {␣
1185
        $address = trim($address);␣
1186
        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim␣
1187
        // Don't validate now addresses with IDN. Will be done in send().␣
1188
        $pos = strrpos($address, '@');␣
1189
        if (false === $pos or␣
1190
            (!$this->has8bitChars(substr($address, ++$pos)) or !static::idnSupported()) and␣
1191
            !static::validateAddress($address)) {␣
1192
            $error_message = sprintf('%s (From): %s',␣
1193
                $this->lang('invalid_address'),␣
1194
                $address);␣
1195
            $this->setError($error_message);␣
1196
            $this->edebug($error_message);␣
1197
            if ($this->exceptions) {␣
1198
                throw new Exception($error_message);␣
1199
            }␣
1200
1201
            return false;␣
1202
        }␣
1203
        $this->From = $address;␣
1204
        $this->FromName = $name;␣
1205
        if ($auto) {␣
1206
            if (empty($this->Sender)) {␣
1207
                $this->Sender = $address;␣
1208
            }␣
1209
        }␣
1210
1211
        return true;␣
1212
    }␣
1213
1214
    /**␣
1215
     * Return the Message-ID header of the last email.␣
1216
     * Technically this is the value from the last time the headers were created,␣
1217
     * but it's also the message ID of the last sent message except in␣
1218
     * pathological cases.␣
1219
     *␣
1220
     * @return string␣
1221
     */␣
1222
    public function getLastMessageID()␣
1223
    {␣
1224
        return $this->lastMessageID;␣
1225
    }␣
1226
1227
    /**␣
1228
     * Check that a string looks like an email address.␣
1229
     * Validation patterns supported:␣
1230
     * * `auto` Pick best pattern automatically;␣
1231
     * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;␣
1232
     * * `pcre` Use old PCRE implementation;␣
1233
     * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;␣
1234
     * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.␣
1235
     * * `noregex` Don't use a regex: super fast, really dumb.␣
1236
     * Alternatively you may pass in a callable to inject your own validator, for example:␣
1237
     *␣
1238
     * ```php␣
1239
     * PHPMailer::validateAddress('user@example.com', function($address) {␣
1240
     *     return (strpos($address, '@') !== false);␣
1241
     * });␣
1242
     * ```␣
1243
     *␣
1244
     * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.␣
1245
     *␣
1246
     * @param string          $address       The email address to check␣
1247
     * @param string|callable $patternselect Which pattern to use␣
1248
     *␣
1249
     * @return bool␣
1250
     */␣
1251
    public static function validateAddress($address, $patternselect = null)␣
1252
    {␣
1253
        if (null === $patternselect) {␣
1254
            $patternselect = static::$validator;␣
1255
        }␣
1256
        if (is_callable($patternselect)) {␣
1257
            return call_user_func($patternselect, $address);␣
1258
        }␣
1259
        //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321␣
1260
        if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {␣
1261
            return false;␣
1262
        }␣
1263
        switch ($patternselect) {␣
1264
            case 'pcre': //Kept for BC␣
1265
            case 'pcre8':␣
1266
                /*␣
1267
                 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL␣
1268
                 * is based.␣
1269
                 * In addition to the addresses allowed by filter_var, also permits:␣
1270
                 *  * dotless domains: `a@b`␣
1271
                 *  * comments: `1234 @ local(blah) .machine .example`␣
1272
                 *  * quoted elements: `'"test blah"@example.org'`␣
1273
                 *  * numeric TLDs: `a@b.123`␣
1274
                 *  * unbracketed IPv4 literals: `a@192.168.0.1`␣
1275
                 *  * IPv6 literals: 'first.last@[IPv6:a1::]'␣
1276
                 * Not all of these will necessarily work for sending!␣
1277
                 *␣
1278
                 * @see       http://squiloople.com/2009/12/20/email-address-validation/␣
1279
                 * @copyright 2009-2010 Michael Rushton␣
1280
                 * Feel free to use and redistribute this code. But please keep this copyright notice.␣
1281
                 */␣
1282
                return (bool) preg_match(␣
1283
                    '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .␣
1284
                    '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .␣
1285
                    '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .␣
1286
                    '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .␣
1287
                    '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .␣
1288
                    '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .␣
1289
                    '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .␣
1290
                    '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .␣
1291
                    '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',␣
1292
                    $address␣
1293
                );␣
1294
            case 'html5':␣
1295
                /*␣
1296
                 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.␣
1297
                 *␣
1298
                 * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)␣
1299
                 */␣
1300
                return (bool) preg_match(␣
1301
                    '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .␣
1302
                    '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',␣
1303
                    $address␣
1304
                );␣
1305
            case 'php':␣
1306
            default:␣
1307
                return (bool) filter_var($address, FILTER_VALIDATE_EMAIL);␣
1308
        }␣
1309
    }␣
1310
1311
    /**␣
1312
     * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the␣
1313
     * `intl` and `mbstring` PHP extensions.␣
1314
     *␣
1315
     * @return bool `true` if required functions for IDN support are present␣
1316
     */␣
1317
    public static function idnSupported()␣
1318
    {␣
1319
        return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');␣
1320
    }␣
1321
1322
    /**␣
1323
     * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.␣
1324
     * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.␣
1325
     * This function silently returns unmodified address if:␣
1326
     * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)␣
1327
     * - Conversion to punycode is impossible (e.g. required PHP functions are not available)␣
1328
     *   or fails for any reason (e.g. domain contains characters not allowed in an IDN).␣
1329
     *␣
1330
     * @see    PHPMailer::$CharSet␣
1331
     *␣
1332
     * @param string $address The email address to convert␣
1333
     *␣
1334
     * @return string The encoded address in ASCII form␣
1335
     */␣
1336
    public function punyencodeAddress($address)␣
1337
    {␣
1338
        // Verify we have required functions, CharSet, and at-sign.␣
1339
        $pos = strrpos($address, '@');␣
1340
        if (static::idnSupported() and␣
1341
            !empty($this->CharSet) and␣
1342
            false !== $pos␣
1343
        ) {␣
1344
            $domain = substr($address, ++$pos);␣
1345
            // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.␣
1346
            if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {␣
1347
                $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);␣
1348
                //Ignore IDE complaints about this line - method signature changed in PHP 5.4␣
1349
                $errorcode = 0;␣
1350
                $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46);␣
1351
                if (false !== $punycode) {␣
1352
                    return substr($address, 0, $pos) . $punycode;␣
1353
                }␣
1354
            }␣
1355
        }␣
1356
1357
        return $address;␣
1358
    }␣
1359
1360
    /**␣
1361
     * Create a message and send it.␣
1362
     * Uses the sending method specified by $Mailer.␣
1363
     *␣
1364
     * @throws Exception␣
1365
     *␣
1366
     * @return bool false on error - See the ErrorInfo property for details of the error␣
1367
     */␣
1368
    public function send()␣
1369
    {␣
1370
        try {␣
1371
            if (!$this->preSend()) {␣
1372
                return false;␣
1373
            }␣
1374
1375
            return $this->postSend();␣
1376
        } catch (Exception $exc) {␣
1377
            $this->mailHeader = '';␣
1378
            $this->setError($exc->getMessage());␣
1379
            if ($this->exceptions) {␣
1380
                throw $exc;␣
1381
            }␣
1382
1383
            return false;␣
1384
        }␣
1385
    }␣
1386
1387
    /**␣
1388
     * Prepare a message for sending.␣
1389
     *␣
1390
     * @throws Exception␣
1391
     *␣
1392
     * @return bool␣
1393
     */␣
1394 3
    public function preSend()␣
1395
    {␣
1396
        if ('smtp' == $this->Mailer or␣
1397
            ('mail' == $this->Mailer and stripos(PHP_OS, 'WIN') === 0)␣
1398
        ) {␣
1399
            //SMTP mandates RFC-compliant line endings␣
1400
            //and it's also used with mail() on Windows␣
1401
            static::setLE("\r\n");␣
1402 1
        } else {␣
1403
            //Maintain backward compatibility with legacy Linux command line mailers␣
1404
            static::setLE(PHP_EOL);␣
1405
        }␣
1406
        //Check for buggy PHP versions that add a header with an incorrect line break␣
1407
        if (ini_get('mail.add_x_header') == 1␣
1408
            and 'mail' == $this->Mailer␣
1409
            and stripos(PHP_OS, 'WIN') === 0␣
1410
            and ((version_compare(PHP_VERSION, '7.0.0', '>=')␣
1411
                    and version_compare(PHP_VERSION, '7.0.17', '<'))␣
1412
                or (version_compare(PHP_VERSION, '7.1.0', '>=')␣
1413
                    and version_compare(PHP_VERSION, '7.1.3', '<')))␣
1414
        ) {␣
1415
            trigger_error(␣
1416
                'Your version of PHP is affected by a bug that may result in corrupted messages.' .␣
1417
                ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .␣
1418
                ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',␣
1419
                E_USER_WARNING␣
1420
            );␣
1421
        }␣
1422
1423
        try {␣
1424
            $this->error_count = 0; // Reset errors␣
1425
            $this->mailHeader = '';␣
1426
1427
            // Dequeue recipient and Reply-To addresses with IDN␣
1428
            foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {␣
1429
                $params[1] = $this->punyencodeAddress($params[1]);␣
1430
                call_user_func_array([$this, 'addAnAddress'], $params);␣
1431
            }␣
1432
            if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {␣
1433
                throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);␣
1434
            }␣
1435
1436
            // Validate From, Sender, and ConfirmReadingTo addresses␣
1437
            foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {␣
1438
                $this->$address_kind = trim($this->$address_kind);␣
1439
                if (empty($this->$address_kind)) {␣
1440
                    continue;␣
1441
                }␣
1442
                $this->$address_kind = $this->punyencodeAddress($this->$address_kind);␣
1443
                if (!static::validateAddress($this->$address_kind)) {␣
1444
                    $error_message = sprintf('%s (%s): %s',␣
1445
                        $this->lang('invalid_address'),␣
1446
                        $address_kind,␣
1447
                        $this->$address_kind);␣
1448
                    $this->setError($error_message);␣
1449
                    $this->edebug($error_message);␣
1450
                    if ($this->exceptions) {␣
1451
                        throw new Exception($error_message);␣
1452
                    }␣
1453
1454
                    return false;␣
1455
                }␣
1456
            }␣
1457
1458
            // Set whether the message is multipart/alternative␣
1459
            if ($this->alternativeExists()) {␣
1460
                $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;␣
1461
            }␣
1462
1463
            $this->setMessageType();␣
1464
            // Refuse to send an empty message unless we are specifically allowing it␣
1465
            if (!$this->AllowEmpty and empty($this->Body)) {␣
1466
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);␣
1467
            }␣
1468
1469
            //Trim subject consistently␣
1470
            $this->Subject = trim($this->Subject);␣
1471
            // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)␣
1472
            $this->MIMEHeader = '';␣
1473
            $this->MIMEBody = $this->createBody();␣
1474
            // createBody may have added some headers, so retain them␣
1475
            $tempheaders = $this->MIMEHeader;␣
1476
            $this->MIMEHeader = $this->createHeader();␣
1477
            $this->MIMEHeader .= $tempheaders;␣
1478
1479
            // To capture the complete message when using mail(), create␣
1480
            // an extra header list which createHeader() doesn't fold in␣
1481
            if ('mail' == $this->Mailer) {␣
1482
                if (count($this->to) > 0) {␣
1483
                    $this->mailHeader .= $this->addrAppend('To', $this->to);␣
1484
                } else {␣
1485
                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');␣
1486
                }␣
1487
                $this->mailHeader .= $this->headerLine(␣
1488
                    'Subject',␣
1489
                    $this->encodeHeader($this->secureHeader($this->Subject))␣
1490
                );␣
1491
            }␣
1492
1493
            // Sign with DKIM if enabled␣
1494
            if (!empty($this->DKIM_domain)␣
1495
                and !empty($this->DKIM_selector)␣
1496
                and (!empty($this->DKIM_private_string)␣
1497
                    or (!empty($this->DKIM_private)␣
1498
                        and static::isPermittedPath($this->DKIM_private)␣
1499
                        and file_exists($this->DKIM_private)␣
1500
                    )␣
1501
                )␣
1502
            ) {␣
1503
                $header_dkim = $this->DKIM_Add(␣
1504
                    $this->MIMEHeader . $this->mailHeader,␣
1505
                    $this->encodeHeader($this->secureHeader($this->Subject)),␣
1506
                    $this->MIMEBody␣
1507
                );␣
1508
                $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .␣
1509
                    static::normalizeBreaks($header_dkim) . static::$LE;␣
1510
            }␣
1511
1512
            return true;␣
1513
        } catch (Exception $exc) {␣
1514
            $this->setError($exc->getMessage());␣
1515
            if ($this->exceptions) {␣
1516
                throw $exc;␣
1517
            }␣
1518
1519
            return false;␣
1520
        }␣
1521
    }␣
1522
1523
    /**␣
1524
     * Actually send a message via the selected mechanism.␣
1525
     *␣
1526
     * @throws Exception␣
1527
     *␣
1528
     * @return bool␣
1529
     */␣
1530
    public function postSend()␣
1531
    {␣
1532
        try {␣
1533
            // Choose the mailer and send through it␣
1534
            switch ($this->Mailer) {␣
1535
                case 'sendmail':␣
1536
                case 'qmail':␣
1537
                    return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);␣
1538
                case 'smtp':␣
1539
                    return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);␣
1540
                case 'mail':␣
1541
                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);␣
1542
                default:␣
1543
                    $sendMethod = $this->Mailer . 'Send';␣
1544
                    if (method_exists($this, $sendMethod)) {␣
1545
                        return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);␣
1546
                    }␣
1547
1548
                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);␣
1549
            }␣
1550
        } catch (Exception $exc) {␣
1551
            $this->setError($exc->getMessage());␣
1552
            $this->edebug($exc->getMessage());␣
1553
            if ($this->exceptions) {␣
1554
                throw $exc;␣
1555
            }␣
1556
        }␣
1557
1558
        return false;␣
1559
    }␣
1560
1561
    /**␣
1562
     * Send mail using the $Sendmail program.␣
1563
     *␣
1564
     * @see    PHPMailer::$Sendmail␣
1565
     *␣
1566
     * @param string $header The message headers␣
1567
     * @param string $body   The message body␣
1568
     *␣
1569
     * @throws Exception␣
1570
     *␣
1571
     * @return bool␣
1572
     */␣
1573 1
    protected function sendmailSend($header, $body)␣
1574
    {␣
1575
        // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.␣
1576
        if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {␣
1577
            if ('qmail' == $this->Mailer) {␣
1578
                $sendmailFmt = '%s -f%s';␣
1579
            } else {␣
1580
                $sendmailFmt = '%s -oi -f%s -t';␣
1581
            }␣
1582
        } else {␣
1583
            if ('qmail' == $this->Mailer) {␣
1584
                $sendmailFmt = '%s';␣
1585
            } else {␣
1586
                $sendmailFmt = '%s -oi -t';␣
1587
            }␣
1588
        }␣
1589
1590
        $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);␣
1591
1592
        if ($this->SingleTo) {␣
1593
            foreach ($this->SingleToArray as $toAddr) {␣
1594
                $mail = @popen($sendmail, 'w');␣
1595
                if (!$mail) {␣
1596
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);␣
1597
                }␣
1598
                fwrite($mail, 'To: ' . $toAddr . "\n");␣
1599
                fwrite($mail, $header);␣
1600
                fwrite($mail, $body);␣
1601
                $result = pclose($mail);␣
1602
                $this->doCallback(␣
1603
                    ($result == 0),␣
1604
                    [$toAddr],␣
1605
                    $this->cc,␣
1606
                    $this->bcc,␣
1607
                    $this->Subject,␣
1608
                    $body,␣
1609
                    $this->From,␣
1610
                    []␣
1611
                );␣
1612
                if (0 !== $result) {␣
1613
                    throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);␣
1614
                }␣
1615
            }␣
1616
        } else {␣
1617
            $mail = @popen($sendmail, 'w');␣
1618
            if (!$mail) {␣
1619
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);␣
1620
            }␣
1621
            fwrite($mail, $header);␣
1622
            fwrite($mail, $body);␣
1623
            $result = pclose($mail);␣
1624
            $this->doCallback(␣
1625
                ($result == 0),␣
1626
                $this->to,␣
1627
                $this->cc,␣
1628
                $this->bcc,␣
1629
                $this->Subject,␣
1630
                $body,␣
1631
                $this->From,␣
1632
                []␣
1633
            );␣
1634
            if (0 !== $result) {␣
1635
                throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);␣
1636
            }␣
1637
        }␣
1638
1639
        return true;␣
1640
    }␣
1641
1642
    /**␣
1643
     * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.␣
1644
     * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.␣
1645
     *␣
1646
     * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report␣
1647
     *␣
1648
     * @param string $string The string to be validated␣
1649
     *␣
1650
     * @return bool␣
1651
     */␣
1652
    protected static function isShellSafe($string)␣
1653
    {␣
1654
        // Future-proof␣
1655
        if (escapeshellcmd($string) !== $string␣
1656
            or !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])␣
1657
        ) {␣
1658
            return false;␣
1659
        }␣
1660
1661
        $length = strlen($string);␣
1662
1663
        for ($i = 0; $i < $length; ++$i) {␣
1664 1
            $c = $string[$i];␣
1665
1666
            // All other characters have a special meaning in at least one common shell, including = and +.␣
1667
            // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.␣
1668
            // Note that this does permit non-Latin alphanumeric characters based on the current locale.␣
1669
            if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {␣
1670
                return false;␣
1671
            }␣
1672
        }␣
1673
1674
        return true;␣
1675
    }␣
1676
1677
    /**␣
1678
     * Check whether a file path is of a permitted type.␣
1679
     * Used to reject URLs and phar files from functions that access local file paths,␣
1680
     * such as addAttachment.␣
1681
     *␣
1682
     * @param string $path A relative or absolute path to a file␣
1683
     *␣
1684
     * @return bool␣
1685
     */␣
1686
    protected static function isPermittedPath($path)␣
1687
    {␣
1688
        return !preg_match('#^[a-z]+://#i', $path);␣
1689
    }␣
1690
1691
    /**␣
1692
     * Send mail using the PHP mail() function.␣
1693
     *␣
1694
     * @see    http://www.php.net/manual/en/book.mail.php␣
1695
     *␣
1696
     * @param string $header The message headers␣
1697
     * @param string $body   The message body␣
1698
     *␣
1699
     * @throws Exception␣
1700
     *␣
1701
     * @return bool␣
1702
     */␣
1703 2
    protected function mailSend($header, $body)␣
1704
    {␣
1705
        $toArr = [];␣
1706
        foreach ($this->to as $toaddr) {␣
1707
            $toArr[] = $this->addrFormat($toaddr);␣
1708
        }␣
1709 1
        $to = implode(', ', $toArr);␣
1710
1711
        $params = null;␣
1712
        //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver␣
1713
        if (!empty($this->Sender) and static::validateAddress($this->Sender)) {␣
1714
            //A space after `-f` is optional, but there is a long history of its presence␣
1715
            //causing problems, so we don't use one␣
1716
            //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html␣
1717
            //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html␣
1718
            //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html␣
1719
            //Example problem: https://www.drupal.org/node/1057954␣
1720
            // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.␣
1721
            if (self::isShellSafe($this->Sender)) {␣
1722
                $params = sprintf('-f%s', $this->Sender);␣
1723
            }␣
1724
        }␣
1725
        if (!empty($this->Sender) and static::validateAddress($this->Sender)) {␣
1726
            $old_from = ini_get('sendmail_from');␣
1727
            ini_set('sendmail_from', $this->Sender);␣
1728
        }␣
1729
        $result = false;␣
1730
        if ($this->SingleTo and count($toArr) > 1) {␣
1731
            foreach ($toArr as $toAddr) {␣
1732
                $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);␣
1733
                $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);␣
1734
            }␣
1735
        } else {␣
1736
            $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);␣
1737
            $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);␣
1738
        }␣
1739
        if (isset($old_from)) {␣
1740
            ini_set('sendmail_from', $old_from);␣
1741
        }␣
1742
        if (!$result) {␣
1743
            throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);␣
1744
        }␣
1745
1746
        return true;␣
1747
    }␣
1748
1749
    /**␣
1750
     * Get an instance to use for SMTP operations.␣
1751
     * Override this function to load your own SMTP implementation,␣
1752
     * or set one with setSMTPInstance.␣
1753
     *␣
1754
     * @return SMTP␣
1755
     */␣
1756
    public function getSMTPInstance()␣
1757
    {␣
1758
        if (!is_object($this->smtp)) {␣
1759
            $this->smtp = new SMTP();␣
1760
        }␣
1761
1762
        return $this->smtp;␣
1763
    }␣
1764
1765
    /**␣
1766
     * Provide an instance to use for SMTP operations.␣
1767
     *␣
1768
     * @param SMTP $smtp␣
1769
     *␣
1770
     * @return SMTP␣
1771
     */␣
1772
    public function setSMTPInstance(SMTP $smtp)␣
1773
    {␣
1774
        $this->smtp = $smtp;␣
1775
1776
        return $this->smtp;␣
1777
    }␣
1778
1779
    /**␣
1780
     * Send mail via SMTP.␣
1781
     * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.␣
1782
     *␣
1783
     * @see PHPMailer::setSMTPInstance() to use a different class.␣
1784
     *␣
1785
     * @uses \PHPMailer\PHPMailer\SMTP␣
1786
     *␣
1787
     * @param string $header The message headers␣
1788
     * @param string $body   The message body␣
1789
     *␣
1790
     * @throws Exception␣
1791
     *␣
1792
     * @return bool␣
1793
     */␣
1794 2
    protected function smtpSend($header, $body)␣
1795
    {␣
1796
        $bad_rcpt = [];␣
1797
        if (!$this->smtpConnect($this->SMTPOptions)) {␣
1798
            throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);␣
1799
        }␣
1800
        //Sender already validated in preSend()␣
1801
        if ('' == $this->Sender) {␣
1802
            $smtp_from = $this->From;␣
1803
        } else {␣
1804
            $smtp_from = $this->Sender;␣
1805
        }␣
1806
        if (!$this->smtp->mail($smtp_from)) {␣
1807
            $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));␣
1808
            throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);␣
1809
        }␣
1810
1811
        $callbacks = [];␣
1812
        // Attempt to send to all recipients␣
1813
        foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {␣
1814
            foreach ($togroup as $to) {␣
1815
                if (!$this->smtp->recipient($to[0], $this->dsn)) {␣
1816
                    $error = $this->smtp->getError();␣
1817
                    $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];␣
1818
                    $isSent = false;␣
1819
                } else {␣
1820
                    $isSent = true;␣
1821
                }␣
1822
1823
                $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];␣
1824
            }␣
1825
        }␣
1826
1827
        // Only send the DATA command if we have viable recipients␣
1828
        if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {␣
1829
            throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);␣
1830
        }␣
1831
1832
        $smtp_transaction_id = $this->smtp->getLastTransactionID();␣
1833
1834
        if ($this->SMTPKeepAlive) {␣
1835
            $this->smtp->reset();␣
1836
        } else {␣
1837
            $this->smtp->quit();␣
1838
            $this->smtp->close();␣
1839
        }␣
1840
1841
        foreach ($callbacks as $cb) {␣
1842
            $this->doCallback(␣
1843
                $cb['issent'],␣
1844
                [$cb['to']],␣
1845
                [],␣
1846
                [],␣
1847
                $this->Subject,␣
1848
                $body,␣
1849
                $this->From,␣
1850
                ['smtp_transaction_id' => $smtp_transaction_id]␣
1851
            );␣
1852
        }␣
1853
1854
        //Create error message for any bad addresses␣
1855
        if (count($bad_rcpt) > 0) {␣
1856
            $errstr = '';␣
1857
            foreach ($bad_rcpt as $bad) {␣
1858
                $errstr .= $bad['to'] . ': ' . $bad['error'];␣
1859
            }␣
1860
            throw new Exception(␣
1861
                $this->lang('recipients_failed') . $errstr,␣
1862
                self::STOP_CONTINUE␣
1863
            );␣
1864
        }␣
1865
1866
        return true;␣
1867
    }␣
1868
1869
    /**␣
1870
     * Initiate a connection to an SMTP server.␣
1871
     * Returns false if the operation failed.␣
1872
     *␣
1873
     * @param array $options An array of options compatible with stream_context_create()␣
1874
     *␣
1875
     * @throws Exception␣
1876
     *␣
1877
     * @uses \PHPMailer\PHPMailer\SMTP␣
1878
     *␣
1879
     * @return bool␣
1880
     */␣
1881 3
    public function smtpConnect($options = null)␣
1882
    {␣
1883
        if (null === $this->smtp) {␣
1884
            $this->smtp = $this->getSMTPInstance();␣
1885
        }␣
1886
1887
        //If no options are provided, use whatever is set in the instance␣
1888
        if (null === $options) {␣
1889
            $options = $this->SMTPOptions;␣
1890
        }␣
1891
1892
        // Already connected?␣
1893
        if ($this->smtp->connected()) {␣
1894
            return true;␣
1895
        }␣
1896
1897
        $this->smtp->setTimeout($this->Timeout);␣
1898
        $this->smtp->setDebugLevel($this->SMTPDebug);␣
1899
        $this->smtp->setDebugOutput($this->Debugoutput);␣
1900
        $this->smtp->setVerp($this->do_verp);␣
1901
        $hosts = explode(';', $this->Host);␣
1902
        $lastexception = null;␣
1903
1904
        foreach ($hosts as $hostentry) {␣
1905
            $hostinfo = [];␣
1906
            if (!preg_match(␣
1907
                '/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/',␣
1908
                trim($hostentry),␣
1909
                $hostinfo␣
1910
            )) {␣
1911
                static::edebug($this->lang('connect_host') . ' ' . $hostentry);␣
1912
                // Not a valid host entry␣
1913
                continue;␣
1914
            }␣
1915
            // $hostinfo[2]: optional ssl or tls prefix␣
1916
            // $hostinfo[3]: the hostname␣
1917
            // $hostinfo[4]: optional port number␣
1918
            // The host string prefix can temporarily override the current setting for SMTPSecure␣
1919
            // If it's not specified, the default value is used␣
1920
1921
            //Check the host name is a valid name or IP address before trying to use it␣
1922
            if (!static::isValidHost($hostinfo[3])) {␣
1923
                static::edebug($this->lang('connect_host') . ' ' . $hostentry);␣
1924
                continue;␣
1925
            }␣
1926
            $prefix = '';␣
1927
            $secure = $this->SMTPSecure;␣
1928
            $tls = ('tls' == $this->SMTPSecure);␣
1929
            if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {␣
1930
                $prefix = 'ssl://';␣
1931
                $tls = false; // Can't have SSL and TLS at the same time␣
1932
                $secure = 'ssl';␣
1933
            } elseif ('tls' == $hostinfo[2]) {␣
1934
                $tls = true;␣
1935
                // tls doesn't use a prefix␣
1936
                $secure = 'tls';␣
1937
            }␣
1938
            //Do we need the OpenSSL extension?␣
1939
            $sslext = defined('OPENSSL_ALGO_SHA256');␣
1940
            if ('tls' === $secure or 'ssl' === $secure) {␣
1941
                //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled␣
1942
                if (!$sslext) {␣
1943
                    throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);␣
1944
                }␣
1945
            }␣
1946
            $host = $hostinfo[3];␣
1947
            $port = $this->Port;␣
1948
            $tport = (int) $hostinfo[4];␣
1949
            if ($tport > 0 and $tport < 65536) {␣
1950
                $port = $tport;␣
1951
            }␣
1952
            if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {␣
1953
                try {␣
1954
                    if ($this->Helo) {␣
1955
                        $hello = $this->Helo;␣
1956
                    } else {␣
1957
                        $hello = $this->serverHostname();␣
1958
                    }␣
1959
                    $this->smtp->hello($hello);␣
1960
                    //Automatically enable TLS encryption if:␣
1961
                    // * it's not disabled␣
1962
                    // * we have openssl extension␣
1963
                    // * we are not already using SSL␣
1964
                    // * the server offers STARTTLS␣
1965
                    if ($this->SMTPAutoTLS and $sslext and 'ssl' != $secure and $this->smtp->getServerExt('STARTTLS')) {␣
1966
                        $tls = true;␣
1967
                    }␣
1968
                    if ($tls) {␣
1969
                        if (!$this->smtp->startTLS()) {␣
1970
                            throw new Exception($this->lang('connect_host'));␣
1971
                        }␣
1972
                        // We must resend EHLO after TLS negotiation␣
1973
                        $this->smtp->hello($hello);␣
1974
                    }␣
1975
                    if ($this->SMTPAuth) {␣
1976
                        if (!$this->smtp->authenticate(␣
1977
                            $this->Username,␣
1978
                            $this->Password,␣
1979
                            $this->AuthType,␣
1980
                            $this->oauth␣
1981
                        )␣
1982
                        ) {␣
1983
                            throw new Exception($this->lang('authenticate'));␣
1984
                        }␣
1985
                    }␣
1986
1987
                    return true;␣
1988
                } catch (Exception $exc) {␣
1989
                    $lastexception = $exc;␣
1990
                    $this->edebug($exc->getMessage());␣
1991
                    // We must have connected, but then failed TLS or Auth, so close connection nicely␣
1992
                    $this->smtp->quit();␣
1993
                }␣
1994
            }␣
1995
        }␣
1996
        // If we get here, all connection attempts have failed, so close connection hard␣
1997
        $this->smtp->close();␣
1998
        // As we've caught all exceptions, just report whatever the last one was␣
1999
        if ($this->exceptions and null !== $lastexception) {␣
2000
            throw $lastexception;␣
2001
        }␣
2002
2003
        return false;␣
2004
    }␣
2005
2006
    /**␣
2007
     * Close the active SMTP session if one exists.␣
2008
     */␣
2009
    public function smtpClose()␣
2010
    {␣
2011
        if (null !== $this->smtp) {␣
2012
            if ($this->smtp->connected()) {␣
2013
                $this->smtp->quit();␣
2014
                $this->smtp->close();␣
2015
            }␣
2016
        }␣
2017
    }␣
2018
2019
    /**␣
2020
     * Set the language for error messages.␣
2021
     * Returns false if it cannot load the language file.␣
2022
     * The default language is English.␣
2023
     *␣
2024
     * @param string $langcode  ISO 639-1 2-character language code (e.g. French is "fr")␣
2025
     * @param string $lang_path Path to the language file directory, with trailing separator (slash)␣
2026
     *␣
2027
     * @return bool␣
2028
     */␣
2029 1
    public function setLanguage($langcode = 'en', $lang_path = '')␣
2030
    {␣
2031
        // Backwards compatibility for renamed language codes␣
2032
        $renamed_langcodes = [␣
2033
            'br' => 'pt_br',␣
2034
            'cz' => 'cs',␣
2035
            'dk' => 'da',␣
2036
            'no' => 'nb',␣
2037
            'se' => 'sv',␣
2038
            'rs' => 'sr',␣
2039
            'tg' => 'tl',␣
2040
        ];␣
2041
2042
        if (isset($renamed_langcodes[$langcode])) {␣
2043
            $langcode = $renamed_langcodes[$langcode];␣
2044
        }␣
2045
2046
        // Define full set of translatable strings in English␣
2047
        $PHPMAILER_LANG = [␣
2048
            'authenticate' => 'SMTP Error: Could not authenticate.',␣
2049
            'connect_host' => 'SMTP Error: Could not connect to SMTP host.',␣
2050
            'data_not_accepted' => 'SMTP Error: data not accepted.',␣
2051
            'empty_message' => 'Message body empty',␣
2052
            'encoding' => 'Unknown encoding: ',␣
2053
            'execute' => 'Could not execute: ',␣
2054
            'file_access' => 'Could not access file: ',␣
2055
            'file_open' => 'File Error: Could not open file: ',␣
2056
            'from_failed' => 'The following From address failed: ',␣
2057
            'instantiate' => 'Could not instantiate mail function.',␣
2058
            'invalid_address' => 'Invalid address: ',␣
2059
            'mailer_not_supported' => ' mailer is not supported.',␣
2060
            'provide_address' => 'You must provide at least one recipient email address.',␣
2061
            'recipients_failed' => 'SMTP Error: The following recipients failed: ',␣
2062
            'signing' => 'Signing Error: ',␣
2063
            'smtp_connect_failed' => 'SMTP connect() failed.',␣
2064
            'smtp_error' => 'SMTP server error: ',␣
2065
            'variable_set' => 'Cannot set or reset variable: ',␣
2066
            'extension_missing' => 'Extension missing: ',␣
2067
        ];␣
2068
        if (empty($lang_path)) {␣
2069
            // Calculate an absolute path so it can work if CWD is not here␣
2070
            $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;␣
2071
        }␣
2072
        //Validate $langcode␣
2073
        if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {␣
2074
            $langcode = 'en';␣
2075
        }␣
2076
        $foundlang = true;␣
2077
        $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';␣
2078
        // There is no English translation file␣
2079
        if ('en' != $langcode) {␣
2080
            // Make sure language file path is readable␣
2081
            if (!static::isPermittedPath($lang_file) || !file_exists($lang_file)) {␣
2082
                $foundlang = false;␣
2083
            } else {␣
2084
                // Overwrite language-specific strings.␣
2085
                // This way we'll never have missing translation keys.␣
2086
                $foundlang = include $lang_file;␣
2087
            }␣
2088
        }␣
2089
        $this->language = $PHPMAILER_LANG;␣
2090
2091
        return (bool) $foundlang; // Returns false if language not found␣
2092
    }␣
2093
2094
    /**␣
2095
     * Get the array of strings for the current language.␣
2096
     *␣
2097
     * @return array␣
2098
     */␣
2099
    public function getTranslations()␣
2100
    {␣
2101
        return $this->language;␣
2102
    }␣
2103
2104
    /**␣
2105
     * Create recipient headers.␣
2106
     *␣
2107
     * @param string $type␣
2108
     * @param array  $addr An array of recipients,␣
2109
     *                     where each recipient is a 2-element indexed array with element 0 containing an address␣
2110
     *                     and element 1 containing a name, like:␣
2111
     *                     [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]␣
2112
     *␣
2113
     * @return string␣
2114
     */␣
2115
    public function addrAppend($type, $addr)␣
2116
    {␣
2117
        $addresses = [];␣
2118
        foreach ($addr as $address) {␣
2119
            $addresses[] = $this->addrFormat($address);␣
2120
        }␣
2121
2122
        return $type . ': ' . implode(', ', $addresses) . static::$LE;␣
2123
    }␣
2124
2125
    /**␣
2126
     * Format an address for use in a message header.␣
2127
     *␣
2128
     * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like␣
2129
     *                    ['joe@example.com', 'Joe User']␣
2130
     *␣
2131
     * @return string␣
2132
     */␣
2133
    public function addrFormat($addr)␣
2134
    {␣
2135
        if (empty($addr[1])) { // No name provided␣
2136
            return $this->secureHeader($addr[0]);␣
2137
        }␣
2138
2139
        return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(␣
2140
                $addr[0]␣
2141
            ) . '>';␣
2142
    }␣
2143
2144
    /**␣
2145
     * Word-wrap message.␣
2146
     * For use with mailers that do not automatically perform wrapping␣
2147
     * and for quoted-printable encoded messages.␣
2148
     * Original written by philippe.␣
2149
     *␣
2150
     * @param string $message The message to wrap␣
2151
     * @param int    $length  The line length to wrap to␣
2152
     * @param bool   $qp_mode Whether to run in Quoted-Printable mode␣
2153
     *␣
2154
     * @return string␣
2155
     */␣
2156 4
    public function wrapText($message, $length, $qp_mode = false)␣
2157
    {␣
2158
        if ($qp_mode) {␣
2159
            $soft_break = sprintf(' =%s', static::$LE);␣
2160
        } else {␣
2161
            $soft_break = static::$LE;␣
2162
        }␣
2163
        // If utf-8 encoding is used, we will need to make sure we don't␣
2164
        // split multibyte characters when we wrap␣
2165
        $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);␣
2166
        $lelen = strlen(static::$LE);␣
2167
        $crlflen = strlen(static::$LE);␣
2168
2169
        $message = static::normalizeBreaks($message);␣
2170
        //Remove a trailing line break␣
2171
        if (substr($message, -$lelen) == static::$LE) {␣
2172
            $message = substr($message, 0, -$lelen);␣
2173
        }␣
2174
2175
        //Split message into lines␣
2176
        $lines = explode(static::$LE, $message);␣
2177
        //Message will be rebuilt in here␣
2178
        $message = '';␣
2179
        foreach ($lines as $line) {␣
2180
            $words = explode(' ', $line);␣
2181
            $buf = '';␣
2182
            $firstword = true;␣
2183
            foreach ($words as $word) {␣
2184
                if ($qp_mode and (strlen($word) > $length)) {␣
2185
                    $space_left = $length - strlen($buf) - $crlflen;␣
2186
                    if (!$firstword) {␣
2187
                        if ($space_left > 20) {␣
2188
                            $len = $space_left;␣
2189
                            if ($is_utf8) {␣
2190
                                $len = $this->utf8CharBoundary($word, $len);␣
2191
                            } elseif ('=' == substr($word, $len - 1, 1)) {␣
2192
                                --$len;␣
2193
                            } elseif ('=' == substr($word, $len - 2, 1)) {␣
2194
                                $len -= 2;␣
2195
                            }␣
2196
                            $part = substr($word, 0, $len);␣
2197
                            $word = substr($word, $len);␣
2198
                            $buf .= ' ' . $part;␣
2199
                            $message .= $buf . sprintf('=%s', static::$LE);␣
2200
                        } else {␣
2201
                            $message .= $buf . $soft_break;␣
2202
                        }␣
2203
                        $buf = '';␣
2204
                    }␣
2205
                    while (strlen($word) > 0) {␣
2206
                        if ($length <= 0) {␣
2207
                            break;␣
2208
                        }␣
2209
                        $len = $length;␣
2210
                        if ($is_utf8) {␣
2211
                            $len = $this->utf8CharBoundary($word, $len);␣
2212
                        } elseif ('=' == substr($word, $len - 1, 1)) {␣
2213
                            --$len;␣
2214
                        } elseif ('=' == substr($word, $len - 2, 1)) {␣
2215
                            $len -= 2;␣
2216
                        }␣
2217
                        $part = substr($word, 0, $len);␣
2218
                        $word = substr($word, $len);␣
2219
2220
                        if (strlen($word) > 0) {␣
2221
                            $message .= $part . sprintf('=%s', static::$LE);␣
2222
                        } else {␣
2223
                            $buf = $part;␣
2224
                        }␣
2225
                    }␣
2226
                } else {␣
2227
                    $buf_o = $buf;␣
2228
                    if (!$firstword) {␣
2229
                        $buf .= ' ';␣
2230
                    }␣
2231
                    $buf .= $word;␣
2232
2233
                    if (strlen($buf) > $length and '' != $buf_o) {␣
2234
                        $message .= $buf_o . $soft_break;␣
2235
                        $buf = $word;␣
2236
                    }␣
2237
                }␣
2238
                $firstword = false;␣
2239
            }␣
2240
            $message .= $buf . static::$LE;␣
2241
        }␣
2242
2243
        return $message;␣
2244
    }␣
2245
2246
    /**␣
2247
     * Find the last character boundary prior to $maxLength in a utf-8␣
2248
     * quoted-printable encoded string.␣
2249
     * Original written by Colin Brown.␣
2250
     *␣
2251
     * @param string $encodedText utf-8 QP text␣
2252
     * @param int    $maxLength   Find the last character boundary prior to this length␣
2253
     *␣
2254
     * @return int␣
2255
     */␣
2256
    public function utf8CharBoundary($encodedText, $maxLength)␣
2257
    {␣
2258
        $foundSplitPos = false;␣
2259
        $lookBack = 3;␣
2260
        while (!$foundSplitPos) {␣
2261
            $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);␣
2262
            $encodedCharPos = strpos($lastChunk, '=');␣
2263
            if (false !== $encodedCharPos) {␣
2264
                // Found start of encoded character byte within $lookBack block.␣
2265
                // Check the encoded byte value (the 2 chars after the '=')␣
2266
                $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);␣
2267
                $dec = hexdec($hex);␣
2268
                if ($dec < 128) {␣
2269
                    // Single byte character.␣
2270
                    // If the encoded char was found at pos 0, it will fit␣
2271
                    // otherwise reduce maxLength to start of the encoded char␣
2272
                    if ($encodedCharPos > 0) {␣
2273
                        $maxLength -= $lookBack - $encodedCharPos;␣
2274
                    }␣
2275
                    $foundSplitPos = true;␣
2276
                } elseif ($dec >= 192) {␣
2277
                    // First byte of a multi byte character␣
2278
                    // Reduce maxLength to split at start of character␣
2279
                    $maxLength -= $lookBack - $encodedCharPos;␣
2280
                    $foundSplitPos = true;␣
2281
                } elseif ($dec < 192) {␣
2282
                    // Middle byte of a multi byte character, look further back␣
2283
                    $lookBack += 3;␣
2284
                }␣
2285
            } else {␣
2286
                // No encoded character found␣
2287
                $foundSplitPos = true;␣
2288
            }␣
2289
        }␣
2290
2291
        return $maxLength;␣
2292
    }␣
2293
2294
    /**␣
2295
     * Apply word wrapping to the message body.␣
2296
     * Wraps the message body to the number of chars set in the WordWrap property.␣
2297
     * You should only do this to plain-text bodies as wrapping HTML tags may break them.␣
2298
     * This is called automatically by createBody(), so you don't need to call it yourself.␣
2299
     */␣
2300
    public function setWordWrap()␣
2301
    {␣
2302
        if ($this->WordWrap < 1) {␣
2303
            return;␣
2304
        }␣
2305
2306
        switch ($this->message_type) {␣
2307
            case 'alt':␣
2308
            case 'alt_inline':␣
2309
            case 'alt_attach':␣
2310
            case 'alt_inline_attach':␣
2311
                $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);␣
2312
                break;␣
2313
            default:␣
2314
                $this->Body = $this->wrapText($this->Body, $this->WordWrap);␣
2315
                break;␣
2316
        }␣
2317
    }␣
2318
2319
    /**␣
2320
     * Assemble message headers.␣
2321
     *␣
2322
     * @return string The assembled headers␣
2323
     */␣
2324 2
    public function createHeader()␣
2325
    {␣
2326
        $result = '';␣
2327
2328
        $result .= $this->headerLine('Date', '' == $this->MessageDate ? self::rfcDate() : $this->MessageDate);␣
2329
2330
        // To be created automatically by mail()␣
2331
        if ($this->SingleTo) {␣
2332
            if ('mail' != $this->Mailer) {␣
2333
                foreach ($this->to as $toaddr) {␣
2334
                    $this->SingleToArray[] = $this->addrFormat($toaddr);␣
2335
                }␣
2336
            }␣
2337
        } else {␣
2338
            if (count($this->to) > 0) {␣
2339
                if ('mail' != $this->Mailer) {␣
2340
                    $result .= $this->addrAppend('To', $this->to);␣
2341
                }␣
2342
            } elseif (count($this->cc) == 0) {␣
2343
                $result .= $this->headerLine('To', 'undisclosed-recipients:;');␣
2344
            }␣
2345
        }␣
2346
2347
        $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);␣
2348
2349
        // sendmail and mail() extract Cc from the header before sending␣
2350
        if (count($this->cc) > 0) {␣
2351
            $result .= $this->addrAppend('Cc', $this->cc);␣
2352
        }␣
2353
2354
        // sendmail and mail() extract Bcc from the header before sending␣
2355
        if ((␣
2356
                'sendmail' == $this->Mailer or 'qmail' == $this->Mailer or 'mail' == $this->Mailer␣
2357
            )␣
2358
            and count($this->bcc) > 0␣
2359
        ) {␣
2360
            $result .= $this->addrAppend('Bcc', $this->bcc);␣
2361
        }␣
2362
2363
        if (count($this->ReplyTo) > 0) {␣
2364
            $result .= $this->addrAppend('Reply-To', $this->ReplyTo);␣
2365
        }␣
2366
2367
        // mail() sets the subject itself␣
2368
        if ('mail' != $this->Mailer) {␣
2369
            $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));␣
2370
        }␣
2371
2372
        // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4␣
2373
        // https://tools.ietf.org/html/rfc5322#section-3.6.4␣
2374
        if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {␣
2375
            $this->lastMessageID = $this->MessageID;␣
2376
        } else {␣
2377
            $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());␣
2378
        }␣
2379
        $result .= $this->headerLine('Message-ID', $this->lastMessageID);␣
2380
        if (null !== $this->Priority) {␣
2381
            $result .= $this->headerLine('X-Priority', $this->Priority);␣
2382
        }␣
2383
        if ('' == $this->XMailer) {␣
2384
            $result .= $this->headerLine(␣
2385
                'X-Mailer',␣
2386
                'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'␣
2387
            );␣
2388
        } else {␣
2389
            $myXmailer = trim($this->XMailer);␣
2390
            if ($myXmailer) {␣
2391
                $result .= $this->headerLine('X-Mailer', $myXmailer);␣
2392
            }␣
2393
        }␣
2394
2395
        if ('' != $this->ConfirmReadingTo) {␣
2396
            $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');␣
2397
        }␣
2398
2399
        // Add custom headers␣
2400
        foreach ($this->CustomHeader as $header) {␣
2401
            $result .= $this->headerLine(␣
2402
                trim($header[0]),␣
2403
                $this->encodeHeader(trim($header[1]))␣
2404
            );␣
2405
        }␣
2406
        if (!$this->sign_key_file) {␣
2407
            $result .= $this->headerLine('MIME-Version', '1.0');␣
2408
            $result .= $this->getMailMIME();␣
2409
        }␣
2410
2411
        return $result;␣
2412
    }␣
2413
2414
    /**␣
2415
     * Get the message MIME type headers.␣
2416
     *␣
2417
     * @return string␣
2418
     */␣
2419 1
    public function getMailMIME()␣
2420
    {␣
2421
        $result = '';␣
2422
        $ismultipart = true;␣
2423
        switch ($this->message_type) {␣
2424
            case 'inline':␣
2425
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');␣
2426
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');␣
2427
                break;␣
2428
            case 'attach':␣
2429
            case 'inline_attach':␣
2430
            case 'alt_attach':␣
2431
            case 'alt_inline_attach':␣
2432
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');␣
2433
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');␣
2434
                break;␣
2435
            case 'alt':␣
2436
            case 'alt_inline':␣
2437
                $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');␣
2438
                $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');␣
2439
                break;␣
2440
            default:␣
2441
                // Catches case 'plain': and case '':␣
2442
                $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);␣
2443
                $ismultipart = false;␣
2444
                break;␣
2445
        }␣
2446
        // RFC1341 part 5 says 7bit is assumed if not specified␣
2447
        if (static::ENCODING_7BIT != $this->Encoding) {␣
2448
            // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE␣
2449
            if ($ismultipart) {␣
2450
                if (static::ENCODING_8BIT == $this->Encoding) {␣
2451
                    $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);␣
2452
                }␣
2453
                // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible␣
2454
            } else {␣
2455
                $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);␣
2456
            }␣
2457
        }␣
2458
2459
        if ('mail' != $this->Mailer) {␣
2460
            $result .= static::$LE;␣
2461
        }␣
2462
2463
        return $result;␣
2464
    }␣
2465
2466
    /**␣
2467
     * Returns the whole MIME message.␣
2468
     * Includes complete headers and body.␣
2469
     * Only valid post preSend().␣
2470
     *␣
2471
     * @see PHPMailer::preSend()␣
2472
     *␣
2473
     * @return string␣
2474
     */␣
2475
    public function getSentMIMEMessage()␣
2476
    {␣
2477
        return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . static::$LE . static::$LE . $this->MIMEBody;␣
2478
    }␣
2479
2480
    /**␣
2481
     * Create a unique ID to use for boundaries.␣
2482
     *␣
2483
     * @return string␣
2484
     */␣
2485
    protected function generateId()␣
2486
    {␣
2487
        $len = 32; //32 bytes = 256 bits␣
2488
        if (function_exists('random_bytes')) {␣
2489
            $bytes = random_bytes($len);␣
2490
        } elseif (function_exists('openssl_random_pseudo_bytes')) {␣
2491
            $bytes = openssl_random_pseudo_bytes($len);␣
2492
        } else {␣
2493
            //Use a hash to force the length to the same as the other methods␣
2494
            $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);␣
2495
        }␣
2496
2497
        //We don't care about messing up base64 format here, just want a random string␣
2498
        return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));␣
2499
    }␣
2500
2501
    /**␣
2502
     * Assemble the message body.␣
2503
     * Returns an empty string on failure.␣
2504
     *␣
2505
     * @throws Exception␣
2506
     *␣
2507
     * @return string The assembled message body␣
2508
     */␣
2509 3
    public function createBody()␣
2510
    {␣
2511
        $body = '';␣
2512
        //Create unique IDs and preset boundaries␣
2513
        $this->uniqueid = $this->generateId();␣
2514
        $this->boundary[1] = 'b1_' . $this->uniqueid;␣
2515
        $this->boundary[2] = 'b2_' . $this->uniqueid;␣
2516
        $this->boundary[3] = 'b3_' . $this->uniqueid;␣
2517
2518
        if ($this->sign_key_file) {␣
2519
            $body .= $this->getMailMIME() . static::$LE;␣
2520
        }␣
2521
2522
        $this->setWordWrap();␣
2523
2524
        $bodyEncoding = $this->Encoding;␣
2525
        $bodyCharSet = $this->CharSet;␣
2526
        //Can we do a 7-bit downgrade?␣
2527
        if (static::ENCODING_8BIT == $bodyEncoding and !$this->has8bitChars($this->Body)) {␣
2528
            $bodyEncoding = static::ENCODING_7BIT;␣
2529
            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit␣
2530
            $bodyCharSet = 'us-ascii';␣
2531
        }␣
2532
        //If lines are too long, and we're not already using an encoding that will shorten them,␣
2533
        //change to quoted-printable transfer encoding for the body part only␣
2534
        if (static::ENCODING_BASE64 != $this->Encoding and static::hasLineLongerThanMax($this->Body)) {␣
2535
            $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;␣
2536
        }␣
2537
2538
        $altBodyEncoding = $this->Encoding;␣
2539
        $altBodyCharSet = $this->CharSet;␣
2540
        //Can we do a 7-bit downgrade?␣
2541
        if (static::ENCODING_8BIT == $altBodyEncoding and !$this->has8bitChars($this->AltBody)) {␣
2542
            $altBodyEncoding = static::ENCODING_7BIT;␣
2543
            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit␣
2544
            $altBodyCharSet = 'us-ascii';␣
2545
        }␣
2546
        //If lines are too long, and we're not already using an encoding that will shorten them,␣
2547
        //change to quoted-printable transfer encoding for the alt body part only␣
2548
        if (static::ENCODING_BASE64 != $altBodyEncoding and static::hasLineLongerThanMax($this->AltBody)) {␣
2549
            $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;␣
2550
        }␣
2551
        //Use this as a preamble in all multipart message types␣
2552
        $mimepre = 'This is a multi-part message in MIME format.' . static::$LE;␣
2553
        switch ($this->message_type) {␣
2554
            case 'inline':␣
2555
                $body .= $mimepre;␣
2556
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);␣
2557
                $body .= $this->encodeString($this->Body, $bodyEncoding);␣
2558
                $body .= static::$LE;␣
2559
                $body .= $this->attachAll('inline', $this->boundary[1]);␣
2560
                break;␣
2561
            case 'attach':␣
2562
                $body .= $mimepre;␣
2563
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);␣
2564
                $body .= $this->encodeString($this->Body, $bodyEncoding);␣
2565
                $body .= static::$LE;␣
2566
                $body .= $this->attachAll('attachment', $this->boundary[1]);␣
2567
                break;␣
2568
            case 'inline_attach':␣
2569
                $body .= $mimepre;␣
2570
                $body .= $this->textLine('--' . $this->boundary[1]);␣
2571
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');␣
2572
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');␣
2573
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');␣
2574
                $body .= static::$LE;␣
2575
                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);␣
2576
                $body .= $this->encodeString($this->Body, $bodyEncoding);␣
2577
                $body .= static::$LE;␣
2578
                $body .= $this->attachAll('inline', $this->boundary[2]);␣
2579
                $body .= static::$LE;␣
2580
                $body .= $this->attachAll('attachment', $this->boundary[1]);␣
2581
                break;␣
2582
            case 'alt':␣
2583
                $body .= $mimepre;␣
2584
                $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);␣
2585
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);␣
2586
                $body .= static::$LE;␣
2587
                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);␣
2588
                $body .= $this->encodeString($this->Body, $bodyEncoding);␣
2589
                $body .= static::$LE;␣
2590
                if (!empty($this->Ical)) {␣
2591
                    $body .= $this->getBoundary($this->boundary[1], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=REQUEST', '');␣
2592
                    $body .= $this->encodeString($this->Ical, $this->Encoding);␣
2593
                    $body .= static::$LE;␣
2594
                }␣
2595
                $body .= $this->endBoundary($this->boundary[1]);␣
2596
                break;␣
2597
            case 'alt_inline':␣
2598
                $body .= $mimepre;␣
2599
                $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);␣
2600
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);␣
2601
                $body .= static::$LE;␣
2602
                $body .= $this->textLine('--' . $this->boundary[1]);␣
2603
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');␣
2604
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');␣
2605
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');␣
2606
                $body .= static::$LE;␣
2607
                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);␣
2608
                $body .= $this->encodeString($this->Body, $bodyEncoding);␣
2609
                $body .= static::$LE;␣
2610
                $body .= $this->attachAll('inline', $this->boundary[2]);␣
2611
                $body .= static::$LE;␣
2612
                $body .= $this->endBoundary($this->boundary[1]);␣
2613
                break;␣
2614
            case 'alt_attach':␣
2615
                $body .= $mimepre;␣
2616
                $body .= $this->textLine('--' . $this->boundary[1]);␣
2617
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');␣
2618
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');␣
2619
                $body .= static::$LE;␣
2620
                $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);␣
2621
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);␣
2622
                $body .= static::$LE;␣
2623
                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);␣
2624
                $body .= $this->encodeString($this->Body, $bodyEncoding);␣
2625
                $body .= static::$LE;␣
2626
                if (!empty($this->Ical)) {␣
2627
                    $body .= $this->getBoundary($this->boundary[2], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=REQUEST', '');␣
2628
                    $body .= $this->encodeString($this->Ical, $this->Encoding);␣
2629
                }␣
2630
                $body .= $this->endBoundary($this->boundary[2]);␣
2631
                $body .= static::$LE;␣
2632
                $body .= $this->attachAll('attachment', $this->boundary[1]);␣
2633
                break;␣
2634
            case 'alt_inline_attach':␣
2635
                $body .= $mimepre;␣
2636
                $body .= $this->textLine('--' . $this->boundary[1]);␣
2637
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');␣
2638
                $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');␣
2639
                $body .= static::$LE;␣
2640
                $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);␣
2641
                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);␣
2642
                $body .= static::$LE;␣
2643
                $body .= $this->textLine('--' . $this->boundary[2]);␣
2644
                $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');␣
2645
                $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";');␣
2646
                $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');␣
2647
                $body .= static::$LE;␣
2648
                $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);␣
2649
                $body .= $this->encodeString($this->Body, $bodyEncoding);␣
2650
                $body .= static::$LE;␣
2651
                $body .= $this->attachAll('inline', $this->boundary[3]);␣
2652
                $body .= static::$LE;␣
2653
                $body .= $this->endBoundary($this->boundary[2]);␣
2654
                $body .= static::$LE;␣
2655
                $body .= $this->attachAll('attachment', $this->boundary[1]);␣
2656
                break;␣
2657
            default:␣
2658
                // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types␣
2659
                //Reset the `Encoding` property in case we changed it for line length reasons␣
2660
                $this->Encoding = $bodyEncoding;␣
2661
                $body .= $this->encodeString($this->Body, $this->Encoding);␣
2662
                break;␣
2663
        }␣
2664
2665
        if ($this->isError()) {␣
2666
            $body = '';␣
2667
            if ($this->exceptions) {␣
2668
                throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);␣
2669
            }␣
2670
        } elseif ($this->sign_key_file) {␣
2671
            try {␣
2672
                if (!defined('PKCS7_TEXT')) {␣
2673
                    throw new Exception($this->lang('extension_missing') . 'openssl');␣
2674
                }␣
2675
                $file = fopen('php://temp', 'rb+');␣
2676
                $signed = fopen('php://temp', 'rb+');␣
2677
                fwrite($file, $body);␣
2678
2679
                //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197␣
2680
                if (empty($this->sign_extracerts_file)) {␣
2681
                    $sign = @openssl_pkcs7_sign(␣
2682
                        $file,␣
2683
                        $signed,␣
2684
                        'file://' . realpath($this->sign_cert_file),␣
2685
                        ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],␣
2686
                        []␣
2687
                    );␣
2688
                } else {␣
2689
                    $sign = @openssl_pkcs7_sign(␣
2690
                        $file,␣
2691
                        $signed,␣
2692
                        'file://' . realpath($this->sign_cert_file),␣
2693
                        ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],␣
2694
                        [],␣
2695
                        PKCS7_DETACHED,␣
2696
                        $this->sign_extracerts_file␣
2697
                    );␣
2698
                }␣
2699
                fclose($file);␣
2700
                if ($sign) {␣
2701
                    $body = file_get_contents($signed);␣
2702
                    fclose($signed);␣
2703
                    //The message returned by openssl contains both headers and body, so need to split them up␣
2704
                    $parts = explode("\n\n", $body, 2);␣
2705
                    $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;␣
2706
                    $body = $parts[1];␣
2707
                } else {␣
2708
                    fclose($signed);␣
2709
                    throw new Exception($this->lang('signing') . openssl_error_string());␣
2710
                }␣
2711
            } catch (Exception $exc) {␣
2712
                $body = '';␣
2713
                if ($this->exceptions) {␣
2714
                    throw $exc;␣
2715
                }␣
2716
            }␣
2717
        }␣
2718
2719
        return $body;␣
2720
    }␣
2721
2722
    /**␣
2723
     * Return the start of a message boundary.␣
2724
     *␣
2725
     * @param string $boundary␣
2726
     * @param string $charSet␣
2727
     * @param string $contentType␣
2728
     * @param string $encoding␣
2729
     *␣
2730
     * @return string␣
2731
     */␣
2732
    protected function getBoundary($boundary, $charSet, $contentType, $encoding)␣
2733
    {␣
2734
        $result = '';␣
2735
        if ('' == $charSet) {␣
2736
            $charSet = $this->CharSet;␣
2737
        }␣
2738
        if ('' == $contentType) {␣
2739
            $contentType = $this->ContentType;␣
2740
        }␣
2741
        if ('' == $encoding) {␣
2742
            $encoding = $this->Encoding;␣
2743
        }␣
2744
        $result .= $this->textLine('--' . $boundary);␣
2745
        $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);␣
2746
        $result .= static::$LE;␣
2747
        // RFC1341 part 5 says 7bit is assumed if not specified␣
2748
        if (static::ENCODING_7BIT != $encoding) {␣
2749
            $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);␣
2750
        }␣
2751
        $result .= static::$LE;␣
2752
2753
        return $result;␣
2754
    }␣
2755
2756
    /**␣
2757
     * Return the end of a message boundary.␣
2758
     *␣
2759
     * @param string $boundary␣
2760
     *␣
2761
     * @return string␣
2762
     */␣
2763
    protected function endBoundary($boundary)␣
2764
    {␣
2765
        return static::$LE . '--' . $boundary . '--' . static::$LE;␣
2766
    }␣
2767
2768
    /**␣
2769
     * Set the message type.␣
2770
     * PHPMailer only supports some preset message types, not arbitrary MIME structures.␣
2771
     */␣
2772
    protected function setMessageType()␣
2773
    {␣
2774
        $type = [];␣
2775
        if ($this->alternativeExists()) {␣
2776
            $type[] = 'alt';␣
2777
        }␣
2778
        if ($this->inlineImageExists()) {␣
2779
            $type[] = 'inline';␣
2780
        }␣
2781
        if ($this->attachmentExists()) {␣
2782
            $type[] = 'attach';␣
2783
        }␣
2784
        $this->message_type = implode('_', $type);␣
2785
        if ('' == $this->message_type) {␣
2786
            //The 'plain' message_type refers to the message having a single body element, not that it is plain-text␣
2787
            $this->message_type = 'plain';␣
2788
        }␣
2789
    }␣
2790
2791
    /**␣
2792
     * Format a header line.␣
2793
     *␣
2794
     * @param string     $name␣
2795
     * @param string|int $value␣
2796
     *␣
2797
     * @return string␣
2798
     */␣
2799
    public function headerLine($name, $value)␣
2800
    {␣
2801
        return $name . ': ' . $value . static::$LE;␣
2802
    }␣
2803
2804
    /**␣
2805
     * Return a formatted mail line.␣
2806
     *␣
2807
     * @param string $value␣
2808
     *␣
2809
     * @return string␣
2810
     */␣
2811
    public function textLine($value)␣
2812
    {␣
2813
        return $value . static::$LE;␣
2814
    }␣
2815
2816
    /**␣
2817
     * Add an attachment from a path on the filesystem.␣
2818
     * Never use a user-supplied path to a file!␣
2819
     * Returns false if the file could not be found or read.␣
2820
     * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.␣
2821
     * If you need to do that, fetch the resource yourself and pass it in via a local file or string.␣
2822
     *␣
2823
     * @param string $path        Path to the attachment␣
2824
     * @param string $name        Overrides the attachment name␣
2825
     * @param string $encoding    File encoding (see $Encoding)␣
2826
     * @param string $type        File extension (MIME) type␣
2827
     * @param string $disposition Disposition to use␣
2828
     *␣
2829
     * @throws Exception␣
2830
     *␣
2831
     * @return bool␣
2832
     */␣
2833
    public function addAttachment(␣
2834
        $path,␣
2835
        $name = '',␣
2836
        $encoding = self::ENCODING_BASE64,␣
2837
        $type = '',␣
2838
        $disposition = 'attachment'␣
2839
    ) {␣
2840
        try {␣
2841
            if (!static::isPermittedPath($path) || !@is_file($path)) {␣
2842
                throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);␣
2843
            }␣
2844
2845
            // If a MIME type is not specified, try to work it out from the file name␣
2846
            if ('' == $type) {␣
2847
                $type = static::filenameToType($path);␣
2848
            }␣
2849
2850
            $filename = static::mb_pathinfo($path, PATHINFO_BASENAME);␣
2851
            if ('' == $name) {␣
2852
                $name = $filename;␣
2853
            }␣
2854
2855
            if (!$this->validateEncoding($encoding)) {␣
2856
                throw new Exception($this->lang('encoding') . $encoding);␣
2857
            }␣
2858
2859
            $this->attachment[] = [␣
2860
                0 => $path,␣
2861
                1 => $filename,␣
2862
                2 => $name,␣
2863
                3 => $encoding,␣
2864
                4 => $type,␣
2865
                5 => false, // isStringAttachment␣
2866
                6 => $disposition,␣
2867
                7 => $name,␣
2868
            ];␣
2869
        } catch (Exception $exc) {␣
2870
            $this->setError($exc->getMessage());␣
2871
            $this->edebug($exc->getMessage());␣
2872
            if ($this->exceptions) {␣
2873
                throw $exc;␣
2874
            }␣
2875
2876
            return false;␣
2877
        }␣
2878
2879
        return true;␣
2880
    }␣
2881
2882
    /**␣
2883
     * Return the array of attachments.␣
2884
     *␣
2885
     * @return array␣
2886
     */␣
2887
    public function getAttachments()␣
2888
    {␣
2889
        return $this->attachment;␣
2890
    }␣
2891
2892
    /**␣
2893
     * Attach all file, string, and binary attachments to the message.␣
2894
     * Returns an empty string on failure.␣
2895
     *␣
2896
     * @param string $disposition_type␣
2897
     * @param string $boundary␣
2898
     *␣
2899
     * @return string␣
2900
     */␣
2901 3
    protected function attachAll($disposition_type, $boundary)␣
2902
    {␣
2903
        // Return text of body␣
2904
        $mime = [];␣
2905
        $cidUniq = [];␣
2906
        $incl = [];␣
2907
2908
        // Add all attachments␣
2909
        foreach ($this->attachment as $attachment) {␣
2910
            // Check if it is a valid disposition_filter␣
2911
            if ($attachment[6] == $disposition_type) {␣
2912
                // Check for string attachment␣
2913
                $string = '';␣
2914
                $path = '';␣
2915
                $bString = $attachment[5];␣
2916
                if ($bString) {␣
2917
                    $string = $attachment[0];␣
2918
                } else {␣
2919
                    $path = $attachment[0];␣
2920
                }␣
2921
2922
                $inclhash = hash('sha256', serialize($attachment));␣
2923
                if (in_array($inclhash, $incl)) {␣
2924
                    continue;␣
2925
                }␣
2926
                $incl[] = $inclhash;␣
2927
                $name = $attachment[2];␣
2928
                $encoding = $attachment[3];␣
2929
                $type = $attachment[4];␣
2930
                $disposition = $attachment[6];␣
2931
                $cid = $attachment[7];␣
2932
                if ('inline' == $disposition and array_key_exists($cid, $cidUniq)) {␣
2933
                    continue;␣
2934
                }␣
2935
                $cidUniq[$cid] = true;␣
2936
2937
                $mime[] = sprintf('--%s%s', $boundary, static::$LE);␣
2938
                //Only include a filename property if we have one␣
2939
                if (!empty($name)) {␣
2940
                    $mime[] = sprintf(␣
2941
                        'Content-Type: %s; name="%s"%s',␣
2942
                        $type,␣
2943
                        $this->encodeHeader($this->secureHeader($name)),␣
2944
                        static::$LE␣
2945
                    );␣
2946
                } else {␣
2947
                    $mime[] = sprintf(␣
2948
                        'Content-Type: %s%s',␣
2949
                        $type,␣
2950
                        static::$LE␣
2951
                    );␣
2952
                }␣
2953
                // RFC1341 part 5 says 7bit is assumed if not specified␣
2954
                if (static::ENCODING_7BIT != $encoding) {␣
2955
                    $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);␣
2956
                }␣
2957
2958
                if (!empty($cid)) {␣
2959
                    $mime[] = sprintf(␣
2960
                        'Content-ID: <%s>%s',␣
2961
                        $this->encodeHeader($this->secureHeader($cid)),␣
2962
                        static::$LE␣
2963
                    );␣
2964
                }␣
2965
2966
                // If a filename contains any of these chars, it should be quoted,␣
2967
                // but not otherwise: RFC2183 & RFC2045 5.1␣
2968
                // Fixes a warning in IETF's msglint MIME checker␣
2969
                // Allow for bypassing the Content-Disposition header totally␣
2970
                if (!empty($disposition)) {␣
2971
                    $encoded_name = $this->encodeHeader($this->secureHeader($name));␣
2972
                    if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {␣
2973
                        $mime[] = sprintf(␣
2974
                            'Content-Disposition: %s; filename="%s"%s',␣
2975
                            $disposition,␣
2976
                            $encoded_name,␣
2977
                            static::$LE . static::$LE␣
2978
                        );␣
2979
                    } else {␣
2980
                        if (!empty($encoded_name)) {␣
2981
                            $mime[] = sprintf(␣
2982
                                'Content-Disposition: %s; filename=%s%s',␣
2983
                                $disposition,␣
2984
                                $encoded_name,␣
2985
                                static::$LE . static::$LE␣
2986
                            );␣
2987
                        } else {␣
2988
                            $mime[] = sprintf(␣
2989
                                'Content-Disposition: %s%s',␣
2990
                                $disposition,␣
2991
                                static::$LE . static::$LE␣
2992
                            );␣
2993
                        }␣
2994
                    }␣
2995
                } else {␣
2996
                    $mime[] = static::$LE;␣
2997
                }␣
2998
2999
                // Encode as string attachment␣
3000
                if ($bString) {␣
3001
                    $mime[] = $this->encodeString($string, $encoding);␣
3002
                } else {␣
3003
                    $mime[] = $this->encodeFile($path, $encoding);␣
3004
                }␣
3005
                if ($this->isError()) {␣
3006
                    return '';␣
3007
                }␣
3008
                $mime[] = static::$LE;␣
3009
            }␣
3010
        }␣
3011
3012
        $mime[] = sprintf('--%s--%s', $boundary, static::$LE);␣
3013
3014
        return implode('', $mime);␣
3015
    }␣
3016
3017
    /**␣
3018
     * Encode a file attachment in requested format.␣
3019
     * Returns an empty string on failure.␣
3020
     *␣
3021
     * @param string $path     The full path to the file␣
3022
     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'␣
3023
     *␣
3024
     * @throws Exception␣
3025
     *␣
3026
     * @return string␣
3027
     */␣
3028
    protected function encodeFile($path, $encoding = self::ENCODING_BASE64)␣
3029
    {␣
3030
        try {␣
3031
            if (!static::isPermittedPath($path) || !file_exists($path)) {␣
3032
                throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);␣
3033
            }␣
3034
            $file_buffer = file_get_contents($path);␣
3035
            if (false === $file_buffer) {␣
3036
                throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);␣
3037
            }␣
3038
            $file_buffer = $this->encodeString($file_buffer, $encoding);␣