[ Index ] |
PHP Cross Reference of WordPress |
[Summary view] [Print] [Text view]
1 <?php 2 3 /** 4 * PHPMailer - PHP email creation and transport class. 5 * PHP Version 5.5. 6 * 7 * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project 8 * 9 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> 10 * @author Jim Jagielski (jimjag) <jimjag@gmail.com> 11 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> 12 * @author Brent R. Matzelle (original founder) 13 * @copyright 2012 - 2020 Marcus Bointon 14 * @copyright 2010 - 2012 Jim Jagielski 15 * @copyright 2004 - 2009 Andy Prevost 16 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License 17 * @note This program is distributed in the hope that it will be useful - WITHOUT 18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 19 * FITNESS FOR A PARTICULAR PURPOSE. 20 */ 21 22 namespace PHPMailer\PHPMailer; 23 24 /** 25 * PHPMailer - PHP email creation and transport class. 26 * 27 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> 28 * @author Jim Jagielski (jimjag) <jimjag@gmail.com> 29 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> 30 * @author Brent R. Matzelle (original founder) 31 */ 32 class PHPMailer 33 { 34 const CHARSET_ASCII = 'us-ascii'; 35 const CHARSET_ISO88591 = 'iso-8859-1'; 36 const CHARSET_UTF8 = 'utf-8'; 37 38 const CONTENT_TYPE_PLAINTEXT = 'text/plain'; 39 const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'; 40 const CONTENT_TYPE_TEXT_HTML = 'text/html'; 41 const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; 42 const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'; 43 const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related'; 44 45 const ENCODING_7BIT = '7bit'; 46 const ENCODING_8BIT = '8bit'; 47 const ENCODING_BASE64 = 'base64'; 48 const ENCODING_BINARY = 'binary'; 49 const ENCODING_QUOTED_PRINTABLE = 'quoted-printable'; 50 51 const ENCRYPTION_STARTTLS = 'tls'; 52 const ENCRYPTION_SMTPS = 'ssl'; 53 54 const ICAL_METHOD_REQUEST = 'REQUEST'; 55 const ICAL_METHOD_PUBLISH = 'PUBLISH'; 56 const ICAL_METHOD_REPLY = 'REPLY'; 57 const ICAL_METHOD_ADD = 'ADD'; 58 const ICAL_METHOD_CANCEL = 'CANCEL'; 59 const ICAL_METHOD_REFRESH = 'REFRESH'; 60 const ICAL_METHOD_COUNTER = 'COUNTER'; 61 const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; 62 63 /** 64 * Email priority. 65 * Options: null (default), 1 = High, 3 = Normal, 5 = low. 66 * When null, the header is not set at all. 67 * 68 * @var int|null 69 */ 70 public $Priority; 71 72 /** 73 * The character set of the message. 74 * 75 * @var string 76 */ 77 public $CharSet = self::CHARSET_ISO88591; 78 79 /** 80 * The MIME Content-type of the message. 81 * 82 * @var string 83 */ 84 public $ContentType = self::CONTENT_TYPE_PLAINTEXT; 85 86 /** 87 * The message encoding. 88 * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". 89 * 90 * @var string 91 */ 92 public $Encoding = self::ENCODING_8BIT; 93 94 /** 95 * Holds the most recent mailer error message. 96 * 97 * @var string 98 */ 99 public $ErrorInfo = ''; 100 101 /** 102 * The From email address for the message. 103 * 104 * @var string 105 */ 106 public $From = 'root@localhost'; 107 108 /** 109 * The From name of the message. 110 * 111 * @var string 112 */ 113 public $FromName = 'Root User'; 114 115 /** 116 * The envelope sender of the message. 117 * This will usually be turned into a Return-Path header by the receiver, 118 * and is the address that bounces will be sent to. 119 * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP. 120 * 121 * @var string 122 */ 123 public $Sender = ''; 124 125 /** 126 * The Subject of the message. 127 * 128 * @var string 129 */ 130 public $Subject = ''; 131 132 /** 133 * An HTML or plain text message body. 134 * If HTML then call isHTML(true). 135 * 136 * @var string 137 */ 138 public $Body = ''; 139 140 /** 141 * The plain-text message body. 142 * This body can be read by mail clients that do not have HTML email 143 * capability such as mutt & Eudora. 144 * Clients that can read HTML will view the normal Body. 145 * 146 * @var string 147 */ 148 public $AltBody = ''; 149 150 /** 151 * An iCal message part body. 152 * Only supported in simple alt or alt_inline message types 153 * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator. 154 * 155 * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ 156 * @see http://kigkonsult.se/iCalcreator/ 157 * 158 * @var string 159 */ 160 public $Ical = ''; 161 162 /** 163 * Value-array of "method" in Contenttype header "text/calendar" 164 * 165 * @var string[] 166 */ 167 protected static $IcalMethods = [ 168 self::ICAL_METHOD_REQUEST, 169 self::ICAL_METHOD_PUBLISH, 170 self::ICAL_METHOD_REPLY, 171 self::ICAL_METHOD_ADD, 172 self::ICAL_METHOD_CANCEL, 173 self::ICAL_METHOD_REFRESH, 174 self::ICAL_METHOD_COUNTER, 175 self::ICAL_METHOD_DECLINECOUNTER, 176 ]; 177 178 /** 179 * The complete compiled MIME message body. 180 * 181 * @var string 182 */ 183 protected $MIMEBody = ''; 184 185 /** 186 * The complete compiled MIME message headers. 187 * 188 * @var string 189 */ 190 protected $MIMEHeader = ''; 191 192 /** 193 * Extra headers that createHeader() doesn't fold in. 194 * 195 * @var string 196 */ 197 protected $mailHeader = ''; 198 199 /** 200 * Word-wrap the message body to this number of chars. 201 * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. 202 * 203 * @see static::STD_LINE_LENGTH 204 * 205 * @var int 206 */ 207 public $WordWrap = 0; 208 209 /** 210 * Which method to use to send mail. 211 * Options: "mail", "sendmail", or "smtp". 212 * 213 * @var string 214 */ 215 public $Mailer = 'mail'; 216 217 /** 218 * The path to the sendmail program. 219 * 220 * @var string 221 */ 222 public $Sendmail = '/usr/sbin/sendmail'; 223 224 /** 225 * Whether mail() uses a fully sendmail-compatible MTA. 226 * One which supports sendmail's "-oi -f" options. 227 * 228 * @var bool 229 */ 230 public $UseSendmailOptions = true; 231 232 /** 233 * The email address that a reading confirmation should be sent to, also known as read receipt. 234 * 235 * @var string 236 */ 237 public $ConfirmReadingTo = ''; 238 239 /** 240 * The hostname to use in the Message-ID header and as default HELO string. 241 * If empty, PHPMailer attempts to find one with, in order, 242 * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value 243 * 'localhost.localdomain'. 244 * 245 * @see PHPMailer::$Helo 246 * 247 * @var string 248 */ 249 public $Hostname = ''; 250 251 /** 252 * An ID to be used in the Message-ID header. 253 * If empty, a unique id will be generated. 254 * You can set your own, but it must be in the format "<id@domain>", 255 * as defined in RFC5322 section 3.6.4 or it will be ignored. 256 * 257 * @see https://tools.ietf.org/html/rfc5322#section-3.6.4 258 * 259 * @var string 260 */ 261 public $MessageID = ''; 262 263 /** 264 * The message Date to be used in the Date header. 265 * If empty, the current date will be added. 266 * 267 * @var string 268 */ 269 public $MessageDate = ''; 270 271 /** 272 * SMTP hosts. 273 * Either a single hostname or multiple semicolon-delimited hostnames. 274 * You can also specify a different port 275 * for each host by using this format: [hostname:port] 276 * (e.g. "smtp1.example.com:25;smtp2.example.com"). 277 * You can also specify encryption type, for example: 278 * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). 279 * Hosts will be tried in order. 280 * 281 * @var string 282 */ 283 public $Host = 'localhost'; 284 285 /** 286 * The default SMTP server port. 287 * 288 * @var int 289 */ 290 public $Port = 25; 291 292 /** 293 * The SMTP HELO/EHLO name used for the SMTP connection. 294 * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find 295 * one with the same method described above for $Hostname. 296 * 297 * @see PHPMailer::$Hostname 298 * 299 * @var string 300 */ 301 public $Helo = ''; 302 303 /** 304 * What kind of encryption to use on the SMTP connection. 305 * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS. 306 * 307 * @var string 308 */ 309 public $SMTPSecure = ''; 310 311 /** 312 * Whether to enable TLS encryption automatically if a server supports it, 313 * even if `SMTPSecure` is not set to 'tls'. 314 * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. 315 * 316 * @var bool 317 */ 318 public $SMTPAutoTLS = true; 319 320 /** 321 * Whether to use SMTP authentication. 322 * Uses the Username and Password properties. 323 * 324 * @see PHPMailer::$Username 325 * @see PHPMailer::$Password 326 * 327 * @var bool 328 */ 329 public $SMTPAuth = false; 330 331 /** 332 * Options array passed to stream_context_create when connecting via SMTP. 333 * 334 * @var array 335 */ 336 public $SMTPOptions = []; 337 338 /** 339 * SMTP username. 340 * 341 * @var string 342 */ 343 public $Username = ''; 344 345 /** 346 * SMTP password. 347 * 348 * @var string 349 */ 350 public $Password = ''; 351 352 /** 353 * SMTP auth type. 354 * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified. 355 * 356 * @var string 357 */ 358 public $AuthType = ''; 359 360 /** 361 * An instance of the PHPMailer OAuth class. 362 * 363 * @var OAuth 364 */ 365 protected $oauth; 366 367 /** 368 * The SMTP server timeout in seconds. 369 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. 370 * 371 * @var int 372 */ 373 public $Timeout = 300; 374 375 /** 376 * Comma separated list of DSN notifications 377 * 'NEVER' under no circumstances a DSN must be returned to the sender. 378 * If you use NEVER all other notifications will be ignored. 379 * 'SUCCESS' will notify you when your mail has arrived at its destination. 380 * 'FAILURE' will arrive if an error occurred during delivery. 381 * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual 382 * delivery's outcome (success or failure) is not yet decided. 383 * 384 * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY 385 */ 386 public $dsn = ''; 387 388 /** 389 * SMTP class debug output mode. 390 * Debug output level. 391 * Options: 392 * @see SMTP::DEBUG_OFF: No output 393 * @see SMTP::DEBUG_CLIENT: Client messages 394 * @see SMTP::DEBUG_SERVER: Client and server messages 395 * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status 396 * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed 397 * 398 * @see SMTP::$do_debug 399 * 400 * @var int 401 */ 402 public $SMTPDebug = 0; 403 404 /** 405 * How to handle debug output. 406 * Options: 407 * * `echo` Output plain-text as-is, appropriate for CLI 408 * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output 409 * * `error_log` Output to error log as configured in php.ini 410 * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise. 411 * Alternatively, you can provide a callable expecting two params: a message string and the debug level: 412 * 413 * ```php 414 * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; 415 * ``` 416 * 417 * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` 418 * level output is used: 419 * 420 * ```php 421 * $mail->Debugoutput = new myPsr3Logger; 422 * ``` 423 * 424 * @see SMTP::$Debugoutput 425 * 426 * @var string|callable|\Psr\Log\LoggerInterface 427 */ 428 public $Debugoutput = 'echo'; 429 430 /** 431 * Whether to keep SMTP connection open after each message. 432 * If this is set to true then to close the connection 433 * requires an explicit call to smtpClose(). 434 * 435 * @var bool 436 */ 437 public $SMTPKeepAlive = false; 438 439 /** 440 * Whether to split multiple to addresses into multiple messages 441 * or send them all in one message. 442 * Only supported in `mail` and `sendmail` transports, not in SMTP. 443 * 444 * @var bool 445 * 446 * @deprecated 6.0.0 PHPMailer isn't a mailing list manager! 447 */ 448 public $SingleTo = false; 449 450 /** 451 * Storage for addresses when SingleTo is enabled. 452 * 453 * @var array 454 */ 455 protected $SingleToArray = []; 456 457 /** 458 * Whether to generate VERP addresses on send. 459 * Only applicable when sending via SMTP. 460 * 461 * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path 462 * @see http://www.postfix.org/VERP_README.html Postfix VERP info 463 * 464 * @var bool 465 */ 466 public $do_verp = false; 467 468 /** 469 * Whether to allow sending messages with an empty body. 470 * 471 * @var bool 472 */ 473 public $AllowEmpty = false; 474 475 /** 476 * DKIM selector. 477 * 478 * @var string 479 */ 480 public $DKIM_selector = ''; 481 482 /** 483 * DKIM Identity. 484 * Usually the email address used as the source of the email. 485 * 486 * @var string 487 */ 488 public $DKIM_identity = ''; 489 490 /** 491 * DKIM passphrase. 492 * Used if your key is encrypted. 493 * 494 * @var string 495 */ 496 public $DKIM_passphrase = ''; 497 498 /** 499 * DKIM signing domain name. 500 * 501 * @example 'example.com' 502 * 503 * @var string 504 */ 505 public $DKIM_domain = ''; 506 507 /** 508 * DKIM Copy header field values for diagnostic use. 509 * 510 * @var bool 511 */ 512 public $DKIM_copyHeaderFields = true; 513 514 /** 515 * DKIM Extra signing headers. 516 * 517 * @example ['List-Unsubscribe', 'List-Help'] 518 * 519 * @var array 520 */ 521 public $DKIM_extraHeaders = []; 522 523 /** 524 * DKIM private key file path. 525 * 526 * @var string 527 */ 528 public $DKIM_private = ''; 529 530 /** 531 * DKIM private key string. 532 * 533 * If set, takes precedence over `$DKIM_private`. 534 * 535 * @var string 536 */ 537 public $DKIM_private_string = ''; 538 539 /** 540 * Callback Action function name. 541 * 542 * The function that handles the result of the send email action. 543 * It is called out by send() for each email sent. 544 * 545 * Value can be any php callable: http://www.php.net/is_callable 546 * 547 * Parameters: 548 * bool $result result of the send action 549 * array $to email addresses of the recipients 550 * array $cc cc email addresses 551 * array $bcc bcc email addresses 552 * string $subject the subject 553 * string $body the email body 554 * string $from email address of sender 555 * string $extra extra information of possible use 556 * "smtp_transaction_id' => last smtp transaction id 557 * 558 * @var string 559 */ 560 public $action_function = ''; 561 562 /** 563 * What to put in the X-Mailer header. 564 * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use. 565 * 566 * @var string|null 567 */ 568 public $XMailer = ''; 569 570 /** 571 * Which validator to use by default when validating email addresses. 572 * May be a callable to inject your own validator, but there are several built-in validators. 573 * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option. 574 * 575 * @see PHPMailer::validateAddress() 576 * 577 * @var string|callable 578 */ 579 public static $validator = 'php'; 580 581 /** 582 * An instance of the SMTP sender class. 583 * 584 * @var SMTP 585 */ 586 protected $smtp; 587 588 /** 589 * The array of 'to' names and addresses. 590 * 591 * @var array 592 */ 593 protected $to = []; 594 595 /** 596 * The array of 'cc' names and addresses. 597 * 598 * @var array 599 */ 600 protected $cc = []; 601 602 /** 603 * The array of 'bcc' names and addresses. 604 * 605 * @var array 606 */ 607 protected $bcc = []; 608 609 /** 610 * The array of reply-to names and addresses. 611 * 612 * @var array 613 */ 614 protected $ReplyTo = []; 615 616 /** 617 * An array of all kinds of addresses. 618 * Includes all of $to, $cc, $bcc. 619 * 620 * @see PHPMailer::$to 621 * @see PHPMailer::$cc 622 * @see PHPMailer::$bcc 623 * 624 * @var array 625 */ 626 protected $all_recipients = []; 627 628 /** 629 * An array of names and addresses queued for validation. 630 * In send(), valid and non duplicate entries are moved to $all_recipients 631 * and one of $to, $cc, or $bcc. 632 * This array is used only for addresses with IDN. 633 * 634 * @see PHPMailer::$to 635 * @see PHPMailer::$cc 636 * @see PHPMailer::$bcc 637 * @see PHPMailer::$all_recipients 638 * 639 * @var array 640 */ 641 protected $RecipientsQueue = []; 642 643 /** 644 * An array of reply-to names and addresses queued for validation. 645 * In send(), valid and non duplicate entries are moved to $ReplyTo. 646 * This array is used only for addresses with IDN. 647 * 648 * @see PHPMailer::$ReplyTo 649 * 650 * @var array 651 */ 652 protected $ReplyToQueue = []; 653 654 /** 655 * The array of attachments. 656 * 657 * @var array 658 */ 659 protected $attachment = []; 660 661 /** 662 * The array of custom headers. 663 * 664 * @var array 665 */ 666 protected $CustomHeader = []; 667 668 /** 669 * The most recent Message-ID (including angular brackets). 670 * 671 * @var string 672 */ 673 protected $lastMessageID = ''; 674 675 /** 676 * The message's MIME type. 677 * 678 * @var string 679 */ 680 protected $message_type = ''; 681 682 /** 683 * The array of MIME boundary strings. 684 * 685 * @var array 686 */ 687 protected $boundary = []; 688 689 /** 690 * The array of available languages. 691 * 692 * @var array 693 */ 694 protected $language = []; 695 696 /** 697 * The number of errors encountered. 698 * 699 * @var int 700 */ 701 protected $error_count = 0; 702 703 /** 704 * The S/MIME certificate file path. 705 * 706 * @var string 707 */ 708 protected $sign_cert_file = ''; 709 710 /** 711 * The S/MIME key file path. 712 * 713 * @var string 714 */ 715 protected $sign_key_file = ''; 716 717 /** 718 * The optional S/MIME extra certificates ("CA Chain") file path. 719 * 720 * @var string 721 */ 722 protected $sign_extracerts_file = ''; 723 724 /** 725 * The S/MIME password for the key. 726 * Used only if the key is encrypted. 727 * 728 * @var string 729 */ 730 protected $sign_key_pass = ''; 731 732 /** 733 * Whether to throw exceptions for errors. 734 * 735 * @var bool 736 */ 737 protected $exceptions = false; 738 739 /** 740 * Unique ID used for message ID and boundaries. 741 * 742 * @var string 743 */ 744 protected $uniqueid = ''; 745 746 /** 747 * The PHPMailer Version number. 748 * 749 * @var string 750 */ 751 const VERSION = '6.4.0'; 752 753 /** 754 * Error severity: message only, continue processing. 755 * 756 * @var int 757 */ 758 const STOP_MESSAGE = 0; 759 760 /** 761 * Error severity: message, likely ok to continue processing. 762 * 763 * @var int 764 */ 765 const STOP_CONTINUE = 1; 766 767 /** 768 * Error severity: message, plus full stop, critical error reached. 769 * 770 * @var int 771 */ 772 const STOP_CRITICAL = 2; 773 774 /** 775 * The SMTP standard CRLF line break. 776 * If you want to change line break format, change static::$LE, not this. 777 */ 778 const CRLF = "\r\n"; 779 780 /** 781 * "Folding White Space" a white space string used for line folding. 782 */ 783 const FWS = ' '; 784 785 /** 786 * SMTP RFC standard line ending; Carriage Return, Line Feed. 787 * 788 * @var string 789 */ 790 protected static $LE = self::CRLF; 791 792 /** 793 * The maximum line length supported by mail(). 794 * 795 * Background: mail() will sometimes corrupt messages 796 * with headers headers longer than 65 chars, see #818. 797 * 798 * @var int 799 */ 800 const MAIL_MAX_LINE_LENGTH = 63; 801 802 /** 803 * The maximum line length allowed by RFC 2822 section 2.1.1. 804 * 805 * @var int 806 */ 807 const MAX_LINE_LENGTH = 998; 808 809 /** 810 * The lower maximum line length allowed by RFC 2822 section 2.1.1. 811 * This length does NOT include the line break 812 * 76 means that lines will be 77 or 78 chars depending on whether 813 * the line break format is LF or CRLF; both are valid. 814 * 815 * @var int 816 */ 817 const STD_LINE_LENGTH = 76; 818 819 /** 820 * Constructor. 821 * 822 * @param bool $exceptions Should we throw external exceptions? 823 */ 824 public function __construct($exceptions = null) 825 { 826 if (null !== $exceptions) { 827 $this->exceptions = (bool) $exceptions; 828 } 829 //Pick an appropriate debug output format automatically 830 $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); 831 } 832 833 /** 834 * Destructor. 835 */ 836 public function __destruct() 837 { 838 //Close any open SMTP connection nicely 839 $this->smtpClose(); 840 } 841 842 /** 843 * Call mail() in a safe_mode-aware fashion. 844 * Also, unless sendmail_path points to sendmail (or something that 845 * claims to be sendmail), don't pass params (not a perfect fix, 846 * but it will do). 847 * 848 * @param string $to To 849 * @param string $subject Subject 850 * @param string $body Message Body 851 * @param string $header Additional Header(s) 852 * @param string|null $params Params 853 * 854 * @return bool 855 */ 856 private function mailPassthru($to, $subject, $body, $header, $params) 857 { 858 //Check overloading of mail function to avoid double-encoding 859 if (ini_get('mbstring.func_overload') & 1) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated 860 $subject = $this->secureHeader($subject); 861 } else { 862 $subject = $this->encodeHeader($this->secureHeader($subject)); 863 } 864 //Calling mail() with null params breaks 865 $this->edebug('Sending with mail()'); 866 $this->edebug('Sendmail path: ' . ini_get('sendmail_path')); 867 $this->edebug("Envelope sender: {$this->Sender}"); 868 $this->edebug("To: {$to}"); 869 $this->edebug("Subject: {$subject}"); 870 $this->edebug("Headers: {$header}"); 871 if (!$this->UseSendmailOptions || null === $params) { 872 $result = @mail($to, $subject, $body, $header); 873 } else { 874 $this->edebug("Additional params: {$params}"); 875 $result = @mail($to, $subject, $body, $header, $params); 876 } 877 $this->edebug('Result: ' . ($result ? 'true' : 'false')); 878 return $result; 879 } 880 881 /** 882 * Output debugging info via a user-defined method. 883 * Only generates output if debug output is enabled. 884 * 885 * @see PHPMailer::$Debugoutput 886 * @see PHPMailer::$SMTPDebug 887 * 888 * @param string $str 889 */ 890 protected function edebug($str) 891 { 892 if ($this->SMTPDebug <= 0) { 893 return; 894 } 895 //Is this a PSR-3 logger? 896 if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { 897 $this->Debugoutput->debug($str); 898 899 return; 900 } 901 //Avoid clash with built-in function names 902 if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { 903 call_user_func($this->Debugoutput, $str, $this->SMTPDebug); 904 905 return; 906 } 907 switch ($this->Debugoutput) { 908 case 'error_log': 909 //Don't output, just log 910 /** @noinspection ForgottenDebugOutputInspection */ 911 error_log($str); 912 break; 913 case 'html': 914 //Cleans up output a bit for a better looking, HTML-safe output 915 echo htmlentities( 916 preg_replace('/[\r\n]+/', '', $str), 917 ENT_QUOTES, 918 'UTF-8' 919 ), "<br>\n"; 920 break; 921 case 'echo': 922 default: 923 //Normalize line breaks 924 $str = preg_replace('/\r\n|\r/m', "\n", $str); 925 echo gmdate('Y-m-d H:i:s'), 926 "\t", 927 //Trim trailing space 928 trim( 929 //Indent for readability, except for trailing break 930 str_replace( 931 "\n", 932 "\n \t ", 933 trim($str) 934 ) 935 ), 936 "\n"; 937 } 938 } 939 940 /** 941 * Sets message type to HTML or plain. 942 * 943 * @param bool $isHtml True for HTML mode 944 */ 945 public function isHTML($isHtml = true) 946 { 947 if ($isHtml) { 948 $this->ContentType = static::CONTENT_TYPE_TEXT_HTML; 949 } else { 950 $this->ContentType = static::CONTENT_TYPE_PLAINTEXT; 951 } 952 } 953 954 /** 955 * Send messages using SMTP. 956 */ 957 public function isSMTP() 958 { 959 $this->Mailer = 'smtp'; 960 } 961 962 /** 963 * Send messages using PHP's mail() function. 964 */ 965 public function isMail() 966 { 967 $this->Mailer = 'mail'; 968 } 969 970 /** 971 * Send messages using $Sendmail. 972 */ 973 public function isSendmail() 974 { 975 $ini_sendmail_path = ini_get('sendmail_path'); 976 977 if (false === stripos($ini_sendmail_path, 'sendmail')) { 978 $this->Sendmail = '/usr/sbin/sendmail'; 979 } else { 980 $this->Sendmail = $ini_sendmail_path; 981 } 982 $this->Mailer = 'sendmail'; 983 } 984 985 /** 986 * Send messages using qmail. 987 */ 988 public function isQmail() 989 { 990 $ini_sendmail_path = ini_get('sendmail_path'); 991 992 if (false === stripos($ini_sendmail_path, 'qmail')) { 993 $this->Sendmail = '/var/qmail/bin/qmail-inject'; 994 } else { 995 $this->Sendmail = $ini_sendmail_path; 996 } 997 $this->Mailer = 'qmail'; 998 } 999 1000 /** 1001 * Add a "To" address. 1002 * 1003 * @param string $address The email address to send to 1004 * @param string $name 1005 * 1006 * @throws Exception 1007 * 1008 * @return bool true on success, false if address already used or invalid in some way 1009 */ 1010 public function addAddress($address, $name = '') 1011 { 1012 return $this->addOrEnqueueAnAddress('to', $address, $name); 1013 } 1014 1015 /** 1016 * Add a "CC" address. 1017 * 1018 * @param string $address The email address to send to 1019 * @param string $name 1020 * 1021 * @throws Exception 1022 * 1023 * @return bool true on success, false if address already used or invalid in some way 1024 */ 1025 public function addCC($address, $name = '') 1026 { 1027 return $this->addOrEnqueueAnAddress('cc', $address, $name); 1028 } 1029 1030 /** 1031 * Add a "BCC" address. 1032 * 1033 * @param string $address The email address to send to 1034 * @param string $name 1035 * 1036 * @throws Exception 1037 * 1038 * @return bool true on success, false if address already used or invalid in some way 1039 */ 1040 public function addBCC($address, $name = '') 1041 { 1042 return $this->addOrEnqueueAnAddress('bcc', $address, $name); 1043 } 1044 1045 /** 1046 * Add a "Reply-To" address. 1047 * 1048 * @param string $address The email address to reply to 1049 * @param string $name 1050 * 1051 * @throws Exception 1052 * 1053 * @return bool true on success, false if address already used or invalid in some way 1054 */ 1055 public function addReplyTo($address, $name = '') 1056 { 1057 return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); 1058 } 1059 1060 /** 1061 * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer 1062 * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still 1063 * be modified after calling this function), addition of such addresses is delayed until send(). 1064 * Addresses that have been added already return false, but do not throw exceptions. 1065 * 1066 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' 1067 * @param string $address The email address to send, resp. to reply to 1068 * @param string $name 1069 * 1070 * @throws Exception 1071 * 1072 * @return bool true on success, false if address already used or invalid in some way 1073 */ 1074 protected function addOrEnqueueAnAddress($kind, $address, $name) 1075 { 1076 $address = trim($address); 1077 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim 1078 $pos = strrpos($address, '@'); 1079 if (false === $pos) { 1080 //At-sign is missing. 1081 $error_message = sprintf( 1082 '%s (%s): %s', 1083 $this->lang('invalid_address'), 1084 $kind, 1085 $address 1086 ); 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 $params = [$kind, $address, $name]; 1096 //Enqueue addresses with IDN until we know the PHPMailer::$CharSet. 1097 if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) { 1098 if ('Reply-To' !== $kind) { 1099 if (!array_key_exists($address, $this->RecipientsQueue)) { 1100 $this->RecipientsQueue[$address] = $params; 1101 1102 return true; 1103 } 1104 } elseif (!array_key_exists($address, $this->ReplyToQueue)) { 1105 $this->ReplyToQueue[$address] = $params; 1106 1107 return true; 1108 } 1109 1110 return false; 1111 } 1112 1113 //Immediately add standard addresses without IDN. 1114 return call_user_func_array([$this, 'addAnAddress'], $params); 1115 } 1116 1117 /** 1118 * Add an address to one of the recipient arrays or to the ReplyTo array. 1119 * Addresses that have been added already return false, but do not throw exceptions. 1120 * 1121 * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' 1122 * @param string $address The email address to send, resp. to reply to 1123 * @param string $name 1124 * 1125 * @throws Exception 1126 * 1127 * @return bool true on success, false if address already used or invalid in some way 1128 */ 1129 protected function addAnAddress($kind, $address, $name = '') 1130 { 1131 if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { 1132 $error_message = sprintf( 1133 '%s: %s', 1134 $this->lang('Invalid recipient kind'), 1135 $kind 1136 ); 1137 $this->setError($error_message); 1138 $this->edebug($error_message); 1139 if ($this->exceptions) { 1140 throw new Exception($error_message); 1141 } 1142 1143 return false; 1144 } 1145 if (!static::validateAddress($address)) { 1146 $error_message = sprintf( 1147 '%s (%s): %s', 1148 $this->lang('invalid_address'), 1149 $kind, 1150 $address 1151 ); 1152 $this->setError($error_message); 1153 $this->edebug($error_message); 1154 if ($this->exceptions) { 1155 throw new Exception($error_message); 1156 } 1157 1158 return false; 1159 } 1160 if ('Reply-To' !== $kind) { 1161 if (!array_key_exists(strtolower($address), $this->all_recipients)) { 1162 $this->{$kind}[] = [$address, $name]; 1163 $this->all_recipients[strtolower($address)] = true; 1164 1165 return true; 1166 } 1167 } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) { 1168 $this->ReplyTo[strtolower($address)] = [$address, $name]; 1169 1170 return true; 1171 } 1172 1173 return false; 1174 } 1175 1176 /** 1177 * Parse and validate a string containing one or more RFC822-style comma-separated email addresses 1178 * of the form "display name <address>" into an array of name/address pairs. 1179 * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. 1180 * Note that quotes in the name part are removed. 1181 * 1182 * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation 1183 * 1184 * @param string $addrstr The address list string 1185 * @param bool $useimap Whether to use the IMAP extension to parse the list 1186 * 1187 * @return array 1188 */ 1189 public static function parseAddresses($addrstr, $useimap = true) 1190 { 1191 $addresses = []; 1192 if ($useimap && function_exists('imap_rfc822_parse_adrlist')) { 1193 //Use this built-in parser if it's available 1194 $list = imap_rfc822_parse_adrlist($addrstr, ''); 1195 foreach ($list as $address) { 1196 if ( 1197 ('.SYNTAX-ERROR.' !== $address->host) && static::validateAddress( 1198 $address->mailbox . '@' . $address->host 1199 ) 1200 ) { 1201 //Decode the name part if it's present and encoded 1202 if ( 1203 property_exists($address, 'personal') && 1204 extension_loaded('mbstring') && 1205 preg_match('/^=\?.*\?=$/', $address->personal) 1206 ) { 1207 $address->personal = mb_decode_mimeheader($address->personal); 1208 } 1209 1210 $addresses[] = [ 1211 'name' => (property_exists($address, 'personal') ? $address->personal : ''), 1212 'address' => $address->mailbox . '@' . $address->host, 1213 ]; 1214 } 1215 } 1216 } else { 1217 //Use this simpler parser 1218 $list = explode(',', $addrstr); 1219 foreach ($list as $address) { 1220 $address = trim($address); 1221 //Is there a separate name part? 1222 if (strpos($address, '<') === false) { 1223 //No separate name, just use the whole thing 1224 if (static::validateAddress($address)) { 1225 $addresses[] = [ 1226 'name' => '', 1227 'address' => $address, 1228 ]; 1229 } 1230 } else { 1231 list($name, $email) = explode('<', $address); 1232 $email = trim(str_replace('>', '', $email)); 1233 $name = trim($name); 1234 if (static::validateAddress($email)) { 1235 //If this name is encoded, decode it 1236 if (preg_match('/^=\?.*\?=$/', $name)) { 1237 $name = mb_decode_mimeheader($name); 1238 } 1239 $addresses[] = [ 1240 //Remove any surrounding quotes and spaces from the name 1241 'name' => trim($name, '\'" '), 1242 'address' => $email, 1243 ]; 1244 } 1245 } 1246 } 1247 } 1248 1249 return $addresses; 1250 } 1251 1252 /** 1253 * Set the From and FromName properties. 1254 * 1255 * @param string $address 1256 * @param string $name 1257 * @param bool $auto Whether to also set the Sender address, defaults to true 1258 * 1259 * @throws Exception 1260 * 1261 * @return bool 1262 */ 1263 public function setFrom($address, $name = '', $auto = true) 1264 { 1265 $address = trim($address); 1266 $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim 1267 //Don't validate now addresses with IDN. Will be done in send(). 1268 $pos = strrpos($address, '@'); 1269 if ( 1270 (false === $pos) 1271 || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported()) 1272 && !static::validateAddress($address)) 1273 ) { 1274 $error_message = sprintf( 1275 '%s (From): %s', 1276 $this->lang('invalid_address'), 1277 $address 1278 ); 1279 $this->setError($error_message); 1280 $this->edebug($error_message); 1281 if ($this->exceptions) { 1282 throw new Exception($error_message); 1283 } 1284 1285 return false; 1286 } 1287 $this->From = $address; 1288 $this->FromName = $name; 1289 if ($auto && empty($this->Sender)) { 1290 $this->Sender = $address; 1291 } 1292 1293 return true; 1294 } 1295 1296 /** 1297 * Return the Message-ID header of the last email. 1298 * Technically this is the value from the last time the headers were created, 1299 * but it's also the message ID of the last sent message except in 1300 * pathological cases. 1301 * 1302 * @return string 1303 */ 1304 public function getLastMessageID() 1305 { 1306 return $this->lastMessageID; 1307 } 1308 1309 /** 1310 * Check that a string looks like an email address. 1311 * Validation patterns supported: 1312 * * `auto` Pick best pattern automatically; 1313 * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0; 1314 * * `pcre` Use old PCRE implementation; 1315 * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; 1316 * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. 1317 * * `noregex` Don't use a regex: super fast, really dumb. 1318 * Alternatively you may pass in a callable to inject your own validator, for example: 1319 * 1320 * ```php 1321 * PHPMailer::validateAddress('user@example.com', function($address) { 1322 * return (strpos($address, '@') !== false); 1323 * }); 1324 * ``` 1325 * 1326 * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. 1327 * 1328 * @param string $address The email address to check 1329 * @param string|callable $patternselect Which pattern to use 1330 * 1331 * @return bool 1332 */ 1333 public static function validateAddress($address, $patternselect = null) 1334 { 1335 if (null === $patternselect) { 1336 $patternselect = static::$validator; 1337 } 1338 if (is_callable($patternselect)) { 1339 return call_user_func($patternselect, $address); 1340 } 1341 //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 1342 if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) { 1343 return false; 1344 } 1345 switch ($patternselect) { 1346 case 'pcre': //Kept for BC 1347 case 'pcre8': 1348 /* 1349 * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL 1350 * is based. 1351 * In addition to the addresses allowed by filter_var, also permits: 1352 * * dotless domains: `a@b` 1353 * * comments: `1234 @ local(blah) .machine .example` 1354 * * quoted elements: `'"test blah"@example.org'` 1355 * * numeric TLDs: `a@b.123` 1356 * * unbracketed IPv4 literals: `a@192.168.0.1` 1357 * * IPv6 literals: 'first.last@[IPv6:a1::]' 1358 * Not all of these will necessarily work for sending! 1359 * 1360 * @see http://squiloople.com/2009/12/20/email-address-validation/ 1361 * @copyright 2009-2010 Michael Rushton 1362 * Feel free to use and redistribute this code. But please keep this copyright notice. 1363 */ 1364 return (bool) preg_match( 1365 '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . 1366 '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . 1367 '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . 1368 '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . 1369 '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . 1370 '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . 1371 '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . 1372 '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . 1373 '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', 1374 $address 1375 ); 1376 case 'html5': 1377 /* 1378 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. 1379 * 1380 * @see https://html.spec.whatwg.org/#e-mail-state-(type=email) 1381 */ 1382 return (bool) preg_match( 1383 '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . 1384 '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', 1385 $address 1386 ); 1387 case 'php': 1388 default: 1389 return filter_var($address, FILTER_VALIDATE_EMAIL) !== false; 1390 } 1391 } 1392 1393 /** 1394 * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the 1395 * `intl` and `mbstring` PHP extensions. 1396 * 1397 * @return bool `true` if required functions for IDN support are present 1398 */ 1399 public static function idnSupported() 1400 { 1401 return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding'); 1402 } 1403 1404 /** 1405 * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. 1406 * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. 1407 * This function silently returns unmodified address if: 1408 * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) 1409 * - Conversion to punycode is impossible (e.g. required PHP functions are not available) 1410 * or fails for any reason (e.g. domain contains characters not allowed in an IDN). 1411 * 1412 * @see PHPMailer::$CharSet 1413 * 1414 * @param string $address The email address to convert 1415 * 1416 * @return string The encoded address in ASCII form 1417 */ 1418 public function punyencodeAddress($address) 1419 { 1420 //Verify we have required functions, CharSet, and at-sign. 1421 $pos = strrpos($address, '@'); 1422 if ( 1423 !empty($this->CharSet) && 1424 false !== $pos && 1425 static::idnSupported() 1426 ) { 1427 $domain = substr($address, ++$pos); 1428 //Verify CharSet string is a valid one, and domain properly encoded in this CharSet. 1429 if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) { 1430 //Convert the domain from whatever charset it's in to UTF-8 1431 $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet); 1432 //Ignore IDE complaints about this line - method signature changed in PHP 5.4 1433 $errorcode = 0; 1434 if (defined('INTL_IDNA_VARIANT_UTS46')) { 1435 //Use the current punycode standard (appeared in PHP 7.2) 1436 $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_UTS46); 1437 } elseif (defined('INTL_IDNA_VARIANT_2003')) { 1438 //Fall back to this old, deprecated/removed encoding 1439 // phpcs:ignore PHPCompatibility.Constants.RemovedConstants.intl_idna_variant_2003Deprecated 1440 $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003); 1441 } else { 1442 //Fall back to a default we don't know about 1443 // phpcs:ignore PHPCompatibility.ParameterValues.NewIDNVariantDefault.NotSet 1444 $punycode = idn_to_ascii($domain, $errorcode); 1445 } 1446 if (false !== $punycode) { 1447 return substr($address, 0, $pos) . $punycode; 1448 } 1449 } 1450 } 1451 1452 return $address; 1453 } 1454 1455 /** 1456 * Create a message and send it. 1457 * Uses the sending method specified by $Mailer. 1458 * 1459 * @throws Exception 1460 * 1461 * @return bool false on error - See the ErrorInfo property for details of the error 1462 */ 1463 public function send() 1464 { 1465 try { 1466 if (!$this->preSend()) { 1467 return false; 1468 } 1469 1470 return $this->postSend(); 1471 } catch (Exception $exc) { 1472 $this->mailHeader = ''; 1473 $this->setError($exc->getMessage()); 1474 if ($this->exceptions) { 1475 throw $exc; 1476 } 1477 1478 return false; 1479 } 1480 } 1481 1482 /** 1483 * Prepare a message for sending. 1484 * 1485 * @throws Exception 1486 * 1487 * @return bool 1488 */ 1489 public function preSend() 1490 { 1491 if ( 1492 'smtp' === $this->Mailer 1493 || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0)) 1494 ) { 1495 //SMTP mandates RFC-compliant line endings 1496 //and it's also used with mail() on Windows 1497 static::setLE(self::CRLF); 1498 } else { 1499 //Maintain backward compatibility with legacy Linux command line mailers 1500 static::setLE(PHP_EOL); 1501 } 1502 //Check for buggy PHP versions that add a header with an incorrect line break 1503 if ( 1504 'mail' === $this->Mailer 1505 && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017) 1506 || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103)) 1507 && ini_get('mail.add_x_header') === '1' 1508 && stripos(PHP_OS, 'WIN') === 0 1509 ) { 1510 trigger_error( 1511 'Your version of PHP is affected by a bug that may result in corrupted messages.' . 1512 ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . 1513 ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', 1514 E_USER_WARNING 1515 ); 1516 } 1517 1518 try { 1519 $this->error_count = 0; //Reset errors 1520 $this->mailHeader = ''; 1521 1522 //Dequeue recipient and Reply-To addresses with IDN 1523 foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { 1524 $params[1] = $this->punyencodeAddress($params[1]); 1525 call_user_func_array([$this, 'addAnAddress'], $params); 1526 } 1527 if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { 1528 throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL); 1529 } 1530 1531 //Validate From, Sender, and ConfirmReadingTo addresses 1532 foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) { 1533 $this->$address_kind = trim($this->$address_kind); 1534 if (empty($this->$address_kind)) { 1535 continue; 1536 } 1537 $this->$address_kind = $this->punyencodeAddress($this->$address_kind); 1538 if (!static::validateAddress($this->$address_kind)) { 1539 $error_message = sprintf( 1540 '%s (%s): %s', 1541 $this->lang('invalid_address'), 1542 $address_kind, 1543 $this->$address_kind 1544 ); 1545 $this->setError($error_message); 1546 $this->edebug($error_message); 1547 if ($this->exceptions) { 1548 throw new Exception($error_message); 1549 } 1550 1551 return false; 1552 } 1553 } 1554 1555 //Set whether the message is multipart/alternative 1556 if ($this->alternativeExists()) { 1557 $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE; 1558 } 1559 1560 $this->setMessageType(); 1561 //Refuse to send an empty message unless we are specifically allowing it 1562 if (!$this->AllowEmpty && empty($this->Body)) { 1563 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); 1564 } 1565 1566 //Trim subject consistently 1567 $this->Subject = trim($this->Subject); 1568 //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) 1569 $this->MIMEHeader = ''; 1570 $this->MIMEBody = $this->createBody(); 1571 //createBody may have added some headers, so retain them 1572 $tempheaders = $this->MIMEHeader; 1573 $this->MIMEHeader = $this->createHeader(); 1574 $this->MIMEHeader .= $tempheaders; 1575 1576 //To capture the complete message when using mail(), create 1577 //an extra header list which createHeader() doesn't fold in 1578 if ('mail' === $this->Mailer) { 1579 if (count($this->to) > 0) { 1580 $this->mailHeader .= $this->addrAppend('To', $this->to); 1581 } else { 1582 $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); 1583 } 1584 $this->mailHeader .= $this->headerLine( 1585 'Subject', 1586 $this->encodeHeader($this->secureHeader($this->Subject)) 1587 ); 1588 } 1589 1590 //Sign with DKIM if enabled 1591 if ( 1592 !empty($this->DKIM_domain) 1593 && !empty($this->DKIM_selector) 1594 && (!empty($this->DKIM_private_string) 1595 || (!empty($this->DKIM_private) 1596 && static::isPermittedPath($this->DKIM_private) 1597 && file_exists($this->DKIM_private) 1598 ) 1599 ) 1600 ) { 1601 $header_dkim = $this->DKIM_Add( 1602 $this->MIMEHeader . $this->mailHeader, 1603 $this->encodeHeader($this->secureHeader($this->Subject)), 1604 $this->MIMEBody 1605 ); 1606 $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . 1607 static::normalizeBreaks($header_dkim) . static::$LE; 1608 } 1609 1610 return true; 1611 } catch (Exception $exc) { 1612 $this->setError($exc->getMessage()); 1613 if ($this->exceptions) { 1614 throw $exc; 1615 } 1616 1617 return false; 1618 } 1619 } 1620 1621 /** 1622 * Actually send a message via the selected mechanism. 1623 * 1624 * @throws Exception 1625 * 1626 * @return bool 1627 */ 1628 public function postSend() 1629 { 1630 try { 1631 //Choose the mailer and send through it 1632 switch ($this->Mailer) { 1633 case 'sendmail': 1634 case 'qmail': 1635 return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); 1636 case 'smtp': 1637 return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); 1638 case 'mail': 1639 return $this->mailSend($this->MIMEHeader, $this->MIMEBody); 1640 default: 1641 $sendMethod = $this->Mailer . 'Send'; 1642 if (method_exists($this, $sendMethod)) { 1643 return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); 1644 } 1645 1646 return $this->mailSend($this->MIMEHeader, $this->MIMEBody); 1647 } 1648 } catch (Exception $exc) { 1649 if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true) { 1650 $this->smtp->reset(); 1651 } 1652 $this->setError($exc->getMessage()); 1653 $this->edebug($exc->getMessage()); 1654 if ($this->exceptions) { 1655 throw $exc; 1656 } 1657 } 1658 1659 return false; 1660 } 1661 1662 /** 1663 * Send mail using the $Sendmail program. 1664 * 1665 * @see PHPMailer::$Sendmail 1666 * 1667 * @param string $header The message headers 1668 * @param string $body The message body 1669 * 1670 * @throws Exception 1671 * 1672 * @return bool 1673 */ 1674 protected function sendmailSend($header, $body) 1675 { 1676 if ($this->Mailer === 'qmail') { 1677 $this->edebug('Sending with qmail'); 1678 } else { 1679 $this->edebug('Sending with sendmail'); 1680 } 1681 $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; 1682 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver 1683 //A space after `-f` is optional, but there is a long history of its presence 1684 //causing problems, so we don't use one 1685 //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html 1686 //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html 1687 //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html 1688 //Example problem: https://www.drupal.org/node/1057954 1689 if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) { 1690 //PHP config has a sender address we can use 1691 $this->Sender = ini_get('sendmail_from'); 1692 } 1693 //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. 1694 if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { 1695 if ($this->Mailer === 'qmail') { 1696 $sendmailFmt = '%s -f%s'; 1697 } else { 1698 $sendmailFmt = '%s -oi -f%s -t'; 1699 } 1700 } else { 1701 //allow sendmail to choose a default envelope sender. It may 1702 //seem preferable to force it to use the From header as with 1703 //SMTP, but that introduces new problems (see 1704 //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and 1705 //it has historically worked this way. 1706 $sendmailFmt = '%s -oi -t'; 1707 } 1708 1709 $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); 1710 $this->edebug('Sendmail path: ' . $this->Sendmail); 1711 $this->edebug('Sendmail command: ' . $sendmail); 1712 $this->edebug('Envelope sender: ' . $this->Sender); 1713 $this->edebug("Headers: {$header}"); 1714 1715 if ($this->SingleTo) { 1716 foreach ($this->SingleToArray as $toAddr) { 1717 $mail = @popen($sendmail, 'w'); 1718 if (!$mail) { 1719 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 1720 } 1721 $this->edebug("To: {$toAddr}"); 1722 fwrite($mail, 'To: ' . $toAddr . "\n"); 1723 fwrite($mail, $header); 1724 fwrite($mail, $body); 1725 $result = pclose($mail); 1726 $this->doCallback( 1727 ($result === 0), 1728 [$toAddr], 1729 $this->cc, 1730 $this->bcc, 1731 $this->Subject, 1732 $body, 1733 $this->From, 1734 [] 1735 ); 1736 $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); 1737 if (0 !== $result) { 1738 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 1739 } 1740 } 1741 } else { 1742 $mail = @popen($sendmail, 'w'); 1743 if (!$mail) { 1744 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 1745 } 1746 fwrite($mail, $header); 1747 fwrite($mail, $body); 1748 $result = pclose($mail); 1749 $this->doCallback( 1750 ($result === 0), 1751 $this->to, 1752 $this->cc, 1753 $this->bcc, 1754 $this->Subject, 1755 $body, 1756 $this->From, 1757 [] 1758 ); 1759 $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); 1760 if (0 !== $result) { 1761 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 1762 } 1763 } 1764 1765 return true; 1766 } 1767 1768 /** 1769 * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. 1770 * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. 1771 * 1772 * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report 1773 * 1774 * @param string $string The string to be validated 1775 * 1776 * @return bool 1777 */ 1778 protected static function isShellSafe($string) 1779 { 1780 //Future-proof 1781 if ( 1782 escapeshellcmd($string) !== $string 1783 || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) 1784 ) { 1785 return false; 1786 } 1787 1788 $length = strlen($string); 1789 1790 for ($i = 0; $i < $length; ++$i) { 1791 $c = $string[$i]; 1792 1793 //All other characters have a special meaning in at least one common shell, including = and +. 1794 //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. 1795 //Note that this does permit non-Latin alphanumeric characters based on the current locale. 1796 if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { 1797 return false; 1798 } 1799 } 1800 1801 return true; 1802 } 1803 1804 /** 1805 * Check whether a file path is of a permitted type. 1806 * Used to reject URLs and phar files from functions that access local file paths, 1807 * such as addAttachment. 1808 * 1809 * @param string $path A relative or absolute path to a file 1810 * 1811 * @return bool 1812 */ 1813 protected static function isPermittedPath($path) 1814 { 1815 return !preg_match('#^[a-z]+://#i', $path); 1816 } 1817 1818 /** 1819 * Check whether a file path is safe, accessible, and readable. 1820 * 1821 * @param string $path A relative or absolute path to a file 1822 * 1823 * @return bool 1824 */ 1825 protected static function fileIsAccessible($path) 1826 { 1827 $readable = file_exists($path); 1828 //If not a UNC path (expected to start with \\), check read permission, see #2069 1829 if (strpos($path, '\\\\') !== 0) { 1830 $readable = $readable && is_readable($path); 1831 } 1832 return static::isPermittedPath($path) && $readable; 1833 } 1834 1835 /** 1836 * Send mail using the PHP mail() function. 1837 * 1838 * @see http://www.php.net/manual/en/book.mail.php 1839 * 1840 * @param string $header The message headers 1841 * @param string $body The message body 1842 * 1843 * @throws Exception 1844 * 1845 * @return bool 1846 */ 1847 protected function mailSend($header, $body) 1848 { 1849 $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; 1850 1851 $toArr = []; 1852 foreach ($this->to as $toaddr) { 1853 $toArr[] = $this->addrFormat($toaddr); 1854 } 1855 $to = implode(', ', $toArr); 1856 1857 $params = null; 1858 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver 1859 //A space after `-f` is optional, but there is a long history of its presence 1860 //causing problems, so we don't use one 1861 //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html 1862 //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html 1863 //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html 1864 //Example problem: https://www.drupal.org/node/1057954 1865 //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. 1866 if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) { 1867 //PHP config has a sender address we can use 1868 $this->Sender = ini_get('sendmail_from'); 1869 } 1870 if (!empty($this->Sender) && static::validateAddress($this->Sender)) { 1871 if (self::isShellSafe($this->Sender)) { 1872 $params = sprintf('-f%s', $this->Sender); 1873 } 1874 $old_from = ini_get('sendmail_from'); 1875 ini_set('sendmail_from', $this->Sender); 1876 } 1877 $result = false; 1878 if ($this->SingleTo && count($toArr) > 1) { 1879 foreach ($toArr as $toAddr) { 1880 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); 1881 $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); 1882 } 1883 } else { 1884 $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); 1885 $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); 1886 } 1887 if (isset($old_from)) { 1888 ini_set('sendmail_from', $old_from); 1889 } 1890 if (!$result) { 1891 throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); 1892 } 1893 1894 return true; 1895 } 1896 1897 /** 1898 * Get an instance to use for SMTP operations. 1899 * Override this function to load your own SMTP implementation, 1900 * or set one with setSMTPInstance. 1901 * 1902 * @return SMTP 1903 */ 1904 public function getSMTPInstance() 1905 { 1906 if (!is_object($this->smtp)) { 1907 $this->smtp = new SMTP(); 1908 } 1909 1910 return $this->smtp; 1911 } 1912 1913 /** 1914 * Provide an instance to use for SMTP operations. 1915 * 1916 * @return SMTP 1917 */ 1918 public function setSMTPInstance(SMTP $smtp) 1919 { 1920 $this->smtp = $smtp; 1921 1922 return $this->smtp; 1923 } 1924 1925 /** 1926 * Send mail via SMTP. 1927 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. 1928 * 1929 * @see PHPMailer::setSMTPInstance() to use a different class. 1930 * 1931 * @uses \PHPMailer\PHPMailer\SMTP 1932 * 1933 * @param string $header The message headers 1934 * @param string $body The message body 1935 * 1936 * @throws Exception 1937 * 1938 * @return bool 1939 */ 1940 protected function smtpSend($header, $body) 1941 { 1942 $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; 1943 $bad_rcpt = []; 1944 if (!$this->smtpConnect($this->SMTPOptions)) { 1945 throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); 1946 } 1947 //Sender already validated in preSend() 1948 if ('' === $this->Sender) { 1949 $smtp_from = $this->From; 1950 } else { 1951 $smtp_from = $this->Sender; 1952 } 1953 if (!$this->smtp->mail($smtp_from)) { 1954 $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); 1955 throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); 1956 } 1957 1958 $callbacks = []; 1959 //Attempt to send to all recipients 1960 foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { 1961 foreach ($togroup as $to) { 1962 if (!$this->smtp->recipient($to[0], $this->dsn)) { 1963 $error = $this->smtp->getError(); 1964 $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; 1965 $isSent = false; 1966 } else { 1967 $isSent = true; 1968 } 1969 1970 $callbacks[] = ['issent' => $isSent, 'to' => $to[0]]; 1971 } 1972 } 1973 1974 //Only send the DATA command if we have viable recipients 1975 if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { 1976 throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); 1977 } 1978 1979 $smtp_transaction_id = $this->smtp->getLastTransactionID(); 1980 1981 if ($this->SMTPKeepAlive) { 1982 $this->smtp->reset(); 1983 } else { 1984 $this->smtp->quit(); 1985 $this->smtp->close(); 1986 } 1987 1988 foreach ($callbacks as $cb) { 1989 $this->doCallback( 1990 $cb['issent'], 1991 [$cb['to']], 1992 [], 1993 [], 1994 $this->Subject, 1995 $body, 1996 $this->From, 1997 ['smtp_transaction_id' => $smtp_transaction_id] 1998 ); 1999 } 2000 2001 //Create error message for any bad addresses 2002 if (count($bad_rcpt) > 0) { 2003 $errstr = ''; 2004 foreach ($bad_rcpt as $bad) { 2005 $errstr .= $bad['to'] . ': ' . $bad['error']; 2006 } 2007 throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); 2008 } 2009 2010 return true; 2011 } 2012 2013 /** 2014 * Initiate a connection to an SMTP server. 2015 * Returns false if the operation failed. 2016 * 2017 * @param array $options An array of options compatible with stream_context_create() 2018 * 2019 * @throws Exception 2020 * 2021 * @uses \PHPMailer\PHPMailer\SMTP 2022 * 2023 * @return bool 2024 */ 2025 public function smtpConnect($options = null) 2026 { 2027 if (null === $this->smtp) { 2028 $this->smtp = $this->getSMTPInstance(); 2029 } 2030 2031 //If no options are provided, use whatever is set in the instance 2032 if (null === $options) { 2033 $options = $this->SMTPOptions; 2034 } 2035 2036 //Already connected? 2037 if ($this->smtp->connected()) { 2038 return true; 2039 } 2040 2041 $this->smtp->setTimeout($this->Timeout); 2042 $this->smtp->setDebugLevel($this->SMTPDebug); 2043 $this->smtp->setDebugOutput($this->Debugoutput); 2044 $this->smtp->setVerp($this->do_verp); 2045 $hosts = explode(';', $this->Host); 2046 $lastexception = null; 2047 2048 foreach ($hosts as $hostentry) { 2049 $hostinfo = []; 2050 if ( 2051 !preg_match( 2052 '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', 2053 trim($hostentry), 2054 $hostinfo 2055 ) 2056 ) { 2057 $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); 2058 //Not a valid host entry 2059 continue; 2060 } 2061 //$hostinfo[1]: optional ssl or tls prefix 2062 //$hostinfo[2]: the hostname 2063 //$hostinfo[3]: optional port number 2064 //The host string prefix can temporarily override the current setting for SMTPSecure 2065 //If it's not specified, the default value is used 2066 2067 //Check the host name is a valid name or IP address before trying to use it 2068 if (!static::isValidHost($hostinfo[2])) { 2069 $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); 2070 continue; 2071 } 2072 $prefix = ''; 2073 $secure = $this->SMTPSecure; 2074 $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure); 2075 if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) { 2076 $prefix = 'ssl://'; 2077 $tls = false; //Can't have SSL and TLS at the same time 2078 $secure = static::ENCRYPTION_SMTPS; 2079 } elseif ('tls' === $hostinfo[1]) { 2080 $tls = true; 2081 //TLS doesn't use a prefix 2082 $secure = static::ENCRYPTION_STARTTLS; 2083 } 2084 //Do we need the OpenSSL extension? 2085 $sslext = defined('OPENSSL_ALGO_SHA256'); 2086 if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { 2087 //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled 2088 if (!$sslext) { 2089 throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); 2090 } 2091 } 2092 $host = $hostinfo[2]; 2093 $port = $this->Port; 2094 if ( 2095 array_key_exists(3, $hostinfo) && 2096 is_numeric($hostinfo[3]) && 2097 $hostinfo[3] > 0 && 2098 $hostinfo[3] < 65536 2099 ) { 2100 $port = (int) $hostinfo[3]; 2101 } 2102 if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { 2103 try { 2104 if ($this->Helo) { 2105 $hello = $this->Helo; 2106 } else { 2107 $hello = $this->serverHostname(); 2108 } 2109 $this->smtp->hello($hello); 2110 //Automatically enable TLS encryption if: 2111 //* it's not disabled 2112 //* we have openssl extension 2113 //* we are not already using SSL 2114 //* the server offers STARTTLS 2115 if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) { 2116 $tls = true; 2117 } 2118 if ($tls) { 2119 if (!$this->smtp->startTLS()) { 2120 throw new Exception($this->lang('connect_host')); 2121 } 2122 //We must resend EHLO after TLS negotiation 2123 $this->smtp->hello($hello); 2124 } 2125 if ( 2126 $this->SMTPAuth && !$this->smtp->authenticate( 2127 $this->Username, 2128 $this->Password, 2129 $this->AuthType, 2130 $this->oauth 2131 ) 2132 ) { 2133 throw new Exception($this->lang('authenticate')); 2134 } 2135 2136 return true; 2137 } catch (Exception $exc) { 2138 $lastexception = $exc; 2139 $this->edebug($exc->getMessage()); 2140 //We must have connected, but then failed TLS or Auth, so close connection nicely 2141 $this->smtp->quit(); 2142 } 2143 } 2144 } 2145 //If we get here, all connection attempts have failed, so close connection hard 2146 $this->smtp->close(); 2147 //As we've caught all exceptions, just report whatever the last one was 2148 if ($this->exceptions && null !== $lastexception) { 2149 throw $lastexception; 2150 } 2151 2152 return false; 2153 } 2154 2155 /** 2156 * Close the active SMTP session if one exists. 2157 */ 2158 public function smtpClose() 2159 { 2160 if ((null !== $this->smtp) && $this->smtp->connected()) { 2161 $this->smtp->quit(); 2162 $this->smtp->close(); 2163 } 2164 } 2165 2166 /** 2167 * Set the language for error messages. 2168 * Returns false if it cannot load the language file. 2169 * The default language is English. 2170 * 2171 * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") 2172 * @param string $lang_path Path to the language file directory, with trailing separator (slash) 2173 * 2174 * @return bool 2175 */ 2176 public function setLanguage($langcode = 'en', $lang_path = '') 2177 { 2178 //Backwards compatibility for renamed language codes 2179 $renamed_langcodes = [ 2180 'br' => 'pt_br', 2181 'cz' => 'cs', 2182 'dk' => 'da', 2183 'no' => 'nb', 2184 'se' => 'sv', 2185 'rs' => 'sr', 2186 'tg' => 'tl', 2187 'am' => 'hy', 2188 ]; 2189 2190 if (array_key_exists($langcode, $renamed_langcodes)) { 2191 $langcode = $renamed_langcodes[$langcode]; 2192 } 2193 2194 //Define full set of translatable strings in English 2195 $PHPMAILER_LANG = [ 2196 'authenticate' => 'SMTP Error: Could not authenticate.', 2197 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 2198 'data_not_accepted' => 'SMTP Error: data not accepted.', 2199 'empty_message' => 'Message body empty', 2200 'encoding' => 'Unknown encoding: ', 2201 'execute' => 'Could not execute: ', 2202 'file_access' => 'Could not access file: ', 2203 'file_open' => 'File Error: Could not open file: ', 2204 'from_failed' => 'The following From address failed: ', 2205 'instantiate' => 'Could not instantiate mail function.', 2206 'invalid_address' => 'Invalid address: ', 2207 'invalid_hostentry' => 'Invalid hostentry: ', 2208 'invalid_host' => 'Invalid host: ', 2209 'mailer_not_supported' => ' mailer is not supported.', 2210 'provide_address' => 'You must provide at least one recipient email address.', 2211 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 2212 'signing' => 'Signing Error: ', 2213 'smtp_connect_failed' => 'SMTP connect() failed.', 2214 'smtp_error' => 'SMTP server error: ', 2215 'variable_set' => 'Cannot set or reset variable: ', 2216 'extension_missing' => 'Extension missing: ', 2217 ]; 2218 if (empty($lang_path)) { 2219 //Calculate an absolute path so it can work if CWD is not here 2220 $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; 2221 } 2222 //Validate $langcode 2223 if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) { 2224 $langcode = 'en'; 2225 } 2226 $foundlang = true; 2227 $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php'; 2228 //There is no English translation file 2229 if ('en' !== $langcode) { 2230 //Make sure language file path is readable 2231 if (!static::fileIsAccessible($lang_file)) { 2232 $foundlang = false; 2233 } else { 2234 //Overwrite language-specific strings. 2235 //This way we'll never have missing translation keys. 2236 $foundlang = include $lang_file; 2237 } 2238 } 2239 $this->language = $PHPMAILER_LANG; 2240 2241 return (bool) $foundlang; //Returns false if language not found 2242 } 2243 2244 /** 2245 * Get the array of strings for the current language. 2246 * 2247 * @return array 2248 */ 2249 public function getTranslations() 2250 { 2251 return $this->language; 2252 } 2253 2254 /** 2255 * Create recipient headers. 2256 * 2257 * @param string $type 2258 * @param array $addr An array of recipients, 2259 * where each recipient is a 2-element indexed array with element 0 containing an address 2260 * and element 1 containing a name, like: 2261 * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']] 2262 * 2263 * @return string 2264 */ 2265 public function addrAppend($type, $addr) 2266 { 2267 $addresses = []; 2268 foreach ($addr as $address) { 2269 $addresses[] = $this->addrFormat($address); 2270 } 2271 2272 return $type . ': ' . implode(', ', $addresses) . static::$LE; 2273 } 2274 2275 /** 2276 * Format an address for use in a message header. 2277 * 2278 * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like 2279 * ['joe@example.com', 'Joe User'] 2280 * 2281 * @return string 2282 */ 2283 public function addrFormat($addr) 2284 { 2285 if (empty($addr[1])) { //No name provided 2286 return $this->secureHeader($addr[0]); 2287 } 2288 2289 return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . 2290 ' <' . $this->secureHeader($addr[0]) . '>'; 2291 } 2292 2293 /** 2294 * Word-wrap message. 2295 * For use with mailers that do not automatically perform wrapping 2296 * and for quoted-printable encoded messages. 2297 * Original written by philippe. 2298 * 2299 * @param string $message The message to wrap 2300 * @param int $length The line length to wrap to 2301 * @param bool $qp_mode Whether to run in Quoted-Printable mode 2302 * 2303 * @return string 2304 */ 2305 public function wrapText($message, $length, $qp_mode = false) 2306 { 2307 if ($qp_mode) { 2308 $soft_break = sprintf(' =%s', static::$LE); 2309 } else { 2310 $soft_break = static::$LE; 2311 } 2312 //If utf-8 encoding is used, we will need to make sure we don't 2313 //split multibyte characters when we wrap 2314 $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet); 2315 $lelen = strlen(static::$LE); 2316 $crlflen = strlen(static::$LE); 2317 2318 $message = static::normalizeBreaks($message); 2319 //Remove a trailing line break 2320 if (substr($message, -$lelen) === static::$LE) { 2321 $message = substr($message, 0, -$lelen); 2322 } 2323 2324 //Split message into lines 2325 $lines = explode(static::$LE, $message); 2326 //Message will be rebuilt in here 2327 $message = ''; 2328 foreach ($lines as $line) { 2329 $words = explode(' ', $line); 2330 $buf = ''; 2331 $firstword = true; 2332 foreach ($words as $word) { 2333 if ($qp_mode && (strlen($word) > $length)) { 2334 $space_left = $length - strlen($buf) - $crlflen; 2335 if (!$firstword) { 2336 if ($space_left > 20) { 2337 $len = $space_left; 2338 if ($is_utf8) { 2339 $len = $this->utf8CharBoundary($word, $len); 2340 } elseif ('=' === substr($word, $len - 1, 1)) { 2341 --$len; 2342 } elseif ('=' === substr($word, $len - 2, 1)) { 2343 $len -= 2; 2344 } 2345 $part = substr($word, 0, $len); 2346 $word = substr($word, $len); 2347 $buf .= ' ' . $part; 2348 $message .= $buf . sprintf('=%s', static::$LE); 2349 } else { 2350 $message .= $buf . $soft_break; 2351 } 2352 $buf = ''; 2353 } 2354 while ($word !== '') { 2355 if ($length <= 0) { 2356 break; 2357 } 2358 $len = $length; 2359 if ($is_utf8) { 2360 $len = $this->utf8CharBoundary($word, $len); 2361 } elseif ('=' === substr($word, $len - 1, 1)) { 2362 --$len; 2363 } elseif ('=' === substr($word, $len - 2, 1)) { 2364 $len -= 2; 2365 } 2366 $part = substr($word, 0, $len); 2367 $word = (string) substr($word, $len); 2368 2369 if ($word !== '') { 2370 $message .= $part . sprintf('=%s', static::$LE); 2371 } else { 2372 $buf = $part; 2373 } 2374 } 2375 } else { 2376 $buf_o = $buf; 2377 if (!$firstword) { 2378 $buf .= ' '; 2379 } 2380 $buf .= $word; 2381 2382 if ('' !== $buf_o && strlen($buf) > $length) { 2383 $message .= $buf_o . $soft_break; 2384 $buf = $word; 2385 } 2386 } 2387 $firstword = false; 2388 } 2389 $message .= $buf . static::$LE; 2390 } 2391 2392 return $message; 2393 } 2394 2395 /** 2396 * Find the last character boundary prior to $maxLength in a utf-8 2397 * quoted-printable encoded string. 2398 * Original written by Colin Brown. 2399 * 2400 * @param string $encodedText utf-8 QP text 2401 * @param int $maxLength Find the last character boundary prior to this length 2402 * 2403 * @return int 2404 */ 2405 public function utf8CharBoundary($encodedText, $maxLength) 2406 { 2407 $foundSplitPos = false; 2408 $lookBack = 3; 2409 while (!$foundSplitPos) { 2410 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); 2411 $encodedCharPos = strpos($lastChunk, '='); 2412 if (false !== $encodedCharPos) { 2413 //Found start of encoded character byte within $lookBack block. 2414 //Check the encoded byte value (the 2 chars after the '=') 2415 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); 2416 $dec = hexdec($hex); 2417 if ($dec < 128) { 2418 //Single byte character. 2419 //If the encoded char was found at pos 0, it will fit 2420 //otherwise reduce maxLength to start of the encoded char 2421 if ($encodedCharPos > 0) { 2422 $maxLength -= $lookBack - $encodedCharPos; 2423 } 2424 $foundSplitPos = true; 2425 } elseif ($dec >= 192) { 2426 //First byte of a multi byte character 2427 //Reduce maxLength to split at start of character 2428 $maxLength -= $lookBack - $encodedCharPos; 2429 $foundSplitPos = true; 2430 } elseif ($dec < 192) { 2431 //Middle byte of a multi byte character, look further back 2432 $lookBack += 3; 2433 } 2434 } else { 2435 //No encoded character found 2436 $foundSplitPos = true; 2437 } 2438 } 2439 2440 return $maxLength; 2441 } 2442 2443 /** 2444 * Apply word wrapping to the message body. 2445 * Wraps the message body to the number of chars set in the WordWrap property. 2446 * You should only do this to plain-text bodies as wrapping HTML tags may break them. 2447 * This is called automatically by createBody(), so you don't need to call it yourself. 2448 */ 2449 public function setWordWrap() 2450 { 2451 if ($this->WordWrap < 1) { 2452 return; 2453 } 2454 2455 switch ($this->message_type) { 2456 case 'alt': 2457 case 'alt_inline': 2458 case 'alt_attach': 2459 case 'alt_inline_attach': 2460 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); 2461 break; 2462 default: 2463 $this->Body = $this->wrapText($this->Body, $this->WordWrap); 2464 break; 2465 } 2466 } 2467 2468 /** 2469 * Assemble message headers. 2470 * 2471 * @return string The assembled headers 2472 */ 2473 public function createHeader() 2474 { 2475 $result = ''; 2476 2477 $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate); 2478 2479 //The To header is created automatically by mail(), so needs to be omitted here 2480 if ('mail' !== $this->Mailer) { 2481 if ($this->SingleTo) { 2482 foreach ($this->to as $toaddr) { 2483 $this->SingleToArray[] = $this->addrFormat($toaddr); 2484 } 2485 } elseif (count($this->to) > 0) { 2486 $result .= $this->addrAppend('To', $this->to); 2487 } elseif (count($this->cc) === 0) { 2488 $result .= $this->headerLine('To', 'undisclosed-recipients:;'); 2489 } 2490 } 2491 $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]); 2492 2493 //sendmail and mail() extract Cc from the header before sending 2494 if (count($this->cc) > 0) { 2495 $result .= $this->addrAppend('Cc', $this->cc); 2496 } 2497 2498 //sendmail and mail() extract Bcc from the header before sending 2499 if ( 2500 ( 2501 'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer 2502 ) 2503 && count($this->bcc) > 0 2504 ) { 2505 $result .= $this->addrAppend('Bcc', $this->bcc); 2506 } 2507 2508 if (count($this->ReplyTo) > 0) { 2509 $result .= $this->addrAppend('Reply-To', $this->ReplyTo); 2510 } 2511 2512 //mail() sets the subject itself 2513 if ('mail' !== $this->Mailer) { 2514 $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); 2515 } 2516 2517 //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 2518 //https://tools.ietf.org/html/rfc5322#section-3.6.4 2519 if ('' !== $this->MessageID && preg_match('/^<.*@.*>$/', $this->MessageID)) { 2520 $this->lastMessageID = $this->MessageID; 2521 } else { 2522 $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); 2523 } 2524 $result .= $this->headerLine('Message-ID', $this->lastMessageID); 2525 if (null !== $this->Priority) { 2526 $result .= $this->headerLine('X-Priority', $this->Priority); 2527 } 2528 if ('' === $this->XMailer) { 2529 $result .= $this->headerLine( 2530 'X-Mailer', 2531 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)' 2532 ); 2533 } else { 2534 $myXmailer = trim($this->XMailer); 2535 if ($myXmailer) { 2536 $result .= $this->headerLine('X-Mailer', $myXmailer); 2537 } 2538 } 2539 2540 if ('' !== $this->ConfirmReadingTo) { 2541 $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); 2542 } 2543 2544 //Add custom headers 2545 foreach ($this->CustomHeader as $header) { 2546 $result .= $this->headerLine( 2547 trim($header[0]), 2548 $this->encodeHeader(trim($header[1])) 2549 ); 2550 } 2551 if (!$this->sign_key_file) { 2552 $result .= $this->headerLine('MIME-Version', '1.0'); 2553 $result .= $this->getMailMIME(); 2554 } 2555 2556 return $result; 2557 } 2558 2559 /** 2560 * Get the message MIME type headers. 2561 * 2562 * @return string 2563 */ 2564 public function getMailMIME() 2565 { 2566 $result = ''; 2567 $ismultipart = true; 2568 switch ($this->message_type) { 2569 case 'inline': 2570 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); 2571 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); 2572 break; 2573 case 'attach': 2574 case 'inline_attach': 2575 case 'alt_attach': 2576 case 'alt_inline_attach': 2577 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';'); 2578 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); 2579 break; 2580 case 'alt': 2581 case 'alt_inline': 2582 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); 2583 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); 2584 break; 2585 default: 2586 //Catches case 'plain': and case '': 2587 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); 2588 $ismultipart = false; 2589 break; 2590 } 2591 //RFC1341 part 5 says 7bit is assumed if not specified 2592 if (static::ENCODING_7BIT !== $this->Encoding) { 2593 //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE 2594 if ($ismultipart) { 2595 if (static::ENCODING_8BIT === $this->Encoding) { 2596 $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT); 2597 } 2598 //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible 2599 } else { 2600 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); 2601 } 2602 } 2603 2604 return $result; 2605 } 2606 2607 /** 2608 * Returns the whole MIME message. 2609 * Includes complete headers and body. 2610 * Only valid post preSend(). 2611 * 2612 * @see PHPMailer::preSend() 2613 * 2614 * @return string 2615 */ 2616 public function getSentMIMEMessage() 2617 { 2618 return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) . 2619 static::$LE . static::$LE . $this->MIMEBody; 2620 } 2621 2622 /** 2623 * Create a unique ID to use for boundaries. 2624 * 2625 * @return string 2626 */ 2627 protected function generateId() 2628 { 2629 $len = 32; //32 bytes = 256 bits 2630 $bytes = ''; 2631 if (function_exists('random_bytes')) { 2632 try { 2633 $bytes = random_bytes($len); 2634 } catch (\Exception $e) { 2635 //Do nothing 2636 } 2637 } elseif (function_exists('openssl_random_pseudo_bytes')) { 2638 /** @noinspection CryptographicallySecureRandomnessInspection */ 2639 $bytes = openssl_random_pseudo_bytes($len); 2640 } 2641 if ($bytes === '') { 2642 //We failed to produce a proper random string, so make do. 2643 //Use a hash to force the length to the same as the other methods 2644 $bytes = hash('sha256', uniqid((string) mt_rand(), true), true); 2645 } 2646 2647 //We don't care about messing up base64 format here, just want a random string 2648 return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true))); 2649 } 2650 2651 /** 2652 * Assemble the message body. 2653 * Returns an empty string on failure. 2654 * 2655 * @throws Exception 2656 * 2657 * @return string The assembled message body 2658 */ 2659 public function createBody() 2660 { 2661 $body = ''; 2662 //Create unique IDs and preset boundaries 2663 $this->uniqueid = $this->generateId(); 2664 $this->boundary[1] = 'b1_' . $this->uniqueid; 2665 $this->boundary[2] = 'b2_' . $this->uniqueid; 2666 $this->boundary[3] = 'b3_' . $this->uniqueid; 2667 2668 if ($this->sign_key_file) { 2669 $body .= $this->getMailMIME() . static::$LE; 2670 } 2671 2672 $this->setWordWrap(); 2673 2674 $bodyEncoding = $this->Encoding; 2675 $bodyCharSet = $this->CharSet; 2676 //Can we do a 7-bit downgrade? 2677 if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) { 2678 $bodyEncoding = static::ENCODING_7BIT; 2679 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit 2680 $bodyCharSet = static::CHARSET_ASCII; 2681 } 2682 //If lines are too long, and we're not already using an encoding that will shorten them, 2683 //change to quoted-printable transfer encoding for the body part only 2684 if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) { 2685 $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE; 2686 } 2687 2688 $altBodyEncoding = $this->Encoding; 2689 $altBodyCharSet = $this->CharSet; 2690 //Can we do a 7-bit downgrade? 2691 if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) { 2692 $altBodyEncoding = static::ENCODING_7BIT; 2693 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit 2694 $altBodyCharSet = static::CHARSET_ASCII; 2695 } 2696 //If lines are too long, and we're not already using an encoding that will shorten them, 2697 //change to quoted-printable transfer encoding for the alt body part only 2698 if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) { 2699 $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE; 2700 } 2701 //Use this as a preamble in all multipart message types 2702 $mimepre = 'This is a multi-part message in MIME format.' . static::$LE . static::$LE; 2703 switch ($this->message_type) { 2704 case 'inline': 2705 $body .= $mimepre; 2706 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); 2707 $body .= $this->encodeString($this->Body, $bodyEncoding); 2708 $body .= static::$LE; 2709 $body .= $this->attachAll('inline', $this->boundary[1]); 2710 break; 2711 case 'attach': 2712 $body .= $mimepre; 2713 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); 2714 $body .= $this->encodeString($this->Body, $bodyEncoding); 2715 $body .= static::$LE; 2716 $body .= $this->attachAll('attachment', $this->boundary[1]); 2717 break; 2718 case 'inline_attach': 2719 $body .= $mimepre; 2720 $body .= $this->textLine('--' . $this->boundary[1]); 2721 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); 2722 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); 2723 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); 2724 $body .= static::$LE; 2725 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); 2726 $body .= $this->encodeString($this->Body, $bodyEncoding); 2727 $body .= static::$LE; 2728 $body .= $this->attachAll('inline', $this->boundary[2]); 2729 $body .= static::$LE; 2730 $body .= $this->attachAll('attachment', $this->boundary[1]); 2731 break; 2732 case 'alt': 2733 $body .= $mimepre; 2734 $body .= $this->getBoundary( 2735 $this->boundary[1], 2736 $altBodyCharSet, 2737 static::CONTENT_TYPE_PLAINTEXT, 2738 $altBodyEncoding 2739 ); 2740 $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 2741 $body .= static::$LE; 2742 $body .= $this->getBoundary( 2743 $this->boundary[1], 2744 $bodyCharSet, 2745 static::CONTENT_TYPE_TEXT_HTML, 2746 $bodyEncoding 2747 ); 2748 $body .= $this->encodeString($this->Body, $bodyEncoding); 2749 $body .= static::$LE; 2750 if (!empty($this->Ical)) { 2751 $method = static::ICAL_METHOD_REQUEST; 2752 foreach (static::$IcalMethods as $imethod) { 2753 if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { 2754 $method = $imethod; 2755 break; 2756 } 2757 } 2758 $body .= $this->getBoundary( 2759 $this->boundary[1], 2760 '', 2761 static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, 2762 '' 2763 ); 2764 $body .= $this->encodeString($this->Ical, $this->Encoding); 2765 $body .= static::$LE; 2766 } 2767 $body .= $this->endBoundary($this->boundary[1]); 2768 break; 2769 case 'alt_inline': 2770 $body .= $mimepre; 2771 $body .= $this->getBoundary( 2772 $this->boundary[1], 2773 $altBodyCharSet, 2774 static::CONTENT_TYPE_PLAINTEXT, 2775 $altBodyEncoding 2776 ); 2777 $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 2778 $body .= static::$LE; 2779 $body .= $this->textLine('--' . $this->boundary[1]); 2780 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); 2781 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); 2782 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); 2783 $body .= static::$LE; 2784 $body .= $this->getBoundary( 2785 $this->boundary[2], 2786 $bodyCharSet, 2787 static::CONTENT_TYPE_TEXT_HTML, 2788 $bodyEncoding 2789 ); 2790 $body .= $this->encodeString($this->Body, $bodyEncoding); 2791 $body .= static::$LE; 2792 $body .= $this->attachAll('inline', $this->boundary[2]); 2793 $body .= static::$LE; 2794 $body .= $this->endBoundary($this->boundary[1]); 2795 break; 2796 case 'alt_attach': 2797 $body .= $mimepre; 2798 $body .= $this->textLine('--' . $this->boundary[1]); 2799 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); 2800 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); 2801 $body .= static::$LE; 2802 $body .= $this->getBoundary( 2803 $this->boundary[2], 2804 $altBodyCharSet, 2805 static::CONTENT_TYPE_PLAINTEXT, 2806 $altBodyEncoding 2807 ); 2808 $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 2809 $body .= static::$LE; 2810 $body .= $this->getBoundary( 2811 $this->boundary[2], 2812 $bodyCharSet, 2813 static::CONTENT_TYPE_TEXT_HTML, 2814 $bodyEncoding 2815 ); 2816 $body .= $this->encodeString($this->Body, $bodyEncoding); 2817 $body .= static::$LE; 2818 if (!empty($this->Ical)) { 2819 $method = static::ICAL_METHOD_REQUEST; 2820 foreach (static::$IcalMethods as $imethod) { 2821 if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { 2822 $method = $imethod; 2823 break; 2824 } 2825 } 2826 $body .= $this->getBoundary( 2827 $this->boundary[2], 2828 '', 2829 static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, 2830 '' 2831 ); 2832 $body .= $this->encodeString($this->Ical, $this->Encoding); 2833 } 2834 $body .= $this->endBoundary($this->boundary[2]); 2835 $body .= static::$LE; 2836 $body .= $this->attachAll('attachment', $this->boundary[1]); 2837 break; 2838 case 'alt_inline_attach': 2839 $body .= $mimepre; 2840 $body .= $this->textLine('--' . $this->boundary[1]); 2841 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); 2842 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); 2843 $body .= static::$LE; 2844 $body .= $this->getBoundary( 2845 $this->boundary[2], 2846 $altBodyCharSet, 2847 static::CONTENT_TYPE_PLAINTEXT, 2848 $altBodyEncoding 2849 ); 2850 $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 2851 $body .= static::$LE; 2852 $body .= $this->textLine('--' . $this->boundary[2]); 2853 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); 2854 $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";'); 2855 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); 2856 $body .= static::$LE; 2857 $body .= $this->getBoundary( 2858 $this->boundary[3], 2859 $bodyCharSet, 2860 static::CONTENT_TYPE_TEXT_HTML, 2861 $bodyEncoding 2862 ); 2863 $body .= $this->encodeString($this->Body, $bodyEncoding); 2864 $body .= static::$LE; 2865 $body .= $this->attachAll('inline', $this->boundary[3]); 2866 $body .= static::$LE; 2867 $body .= $this->endBoundary($this->boundary[2]); 2868 $body .= static::$LE; 2869 $body .= $this->attachAll('attachment', $this->boundary[1]); 2870 break; 2871 default: 2872 //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types 2873 //Reset the `Encoding` property in case we changed it for line length reasons 2874 $this->Encoding = $bodyEncoding; 2875 $body .= $this->encodeString($this->Body, $this->Encoding); 2876 break; 2877 } 2878 2879 if ($this->isError()) { 2880 $body = ''; 2881 if ($this->exceptions) { 2882 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); 2883 } 2884 } elseif ($this->sign_key_file) { 2885 try { 2886 if (!defined('PKCS7_TEXT')) { 2887 throw new Exception($this->lang('extension_missing') . 'openssl'); 2888 } 2889 2890 $file = tempnam(sys_get_temp_dir(), 'srcsign'); 2891 $signed = tempnam(sys_get_temp_dir(), 'mailsign'); 2892 file_put_contents($file, $body); 2893 2894 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 2895 if (empty($this->sign_extracerts_file)) { 2896 $sign = @openssl_pkcs7_sign( 2897 $file, 2898 $signed, 2899 'file://' . realpath($this->sign_cert_file), 2900 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], 2901 [] 2902 ); 2903 } else { 2904 $sign = @openssl_pkcs7_sign( 2905 $file, 2906 $signed, 2907 'file://' . realpath($this->sign_cert_file), 2908 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], 2909 [], 2910 PKCS7_DETACHED, 2911 $this->sign_extracerts_file 2912 ); 2913 } 2914 2915 @unlink($file); 2916 if ($sign) { 2917 $body = file_get_contents($signed); 2918 @unlink($signed); 2919 //The message returned by openssl contains both headers and body, so need to split them up 2920 $parts = explode("\n\n", $body, 2); 2921 $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE; 2922 $body = $parts[1]; 2923 } else { 2924 @unlink($signed); 2925 throw new Exception($this->lang('signing') . openssl_error_string()); 2926 } 2927 } catch (Exception $exc) { 2928 $body = ''; 2929 if ($this->exceptions) { 2930 throw $exc; 2931 } 2932 } 2933 } 2934 2935 return $body; 2936 } 2937 2938 /** 2939 * Return the start of a message boundary. 2940 * 2941 * @param string $boundary 2942 * @param string $charSet 2943 * @param string $contentType 2944 * @param string $encoding 2945 * 2946 * @return string 2947 */ 2948 protected function getBoundary($boundary, $charSet, $contentType, $encoding) 2949 { 2950 $result = ''; 2951 if ('' === $charSet) { 2952 $charSet = $this->CharSet; 2953 } 2954 if ('' === $contentType) { 2955 $contentType = $this->ContentType; 2956 } 2957 if ('' === $encoding) { 2958 $encoding = $this->Encoding; 2959 } 2960 $result .= $this->textLine('--' . $boundary); 2961 $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); 2962 $result .= static::$LE; 2963 //RFC1341 part 5 says 7bit is assumed if not specified 2964 if (static::ENCODING_7BIT !== $encoding) { 2965 $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); 2966 } 2967 $result .= static::$LE; 2968 2969 return $result; 2970 } 2971 2972 /** 2973 * Return the end of a message boundary. 2974 * 2975 * @param string $boundary 2976 * 2977 * @return string 2978 */ 2979 protected function endBoundary($boundary) 2980 { 2981 return static::$LE . '--' . $boundary . '--' . static::$LE; 2982 } 2983 2984 /** 2985 * Set the message type. 2986 * PHPMailer only supports some preset message types, not arbitrary MIME structures. 2987 */ 2988 protected function setMessageType() 2989 { 2990 $type = []; 2991 if ($this->alternativeExists()) { 2992 $type[] = 'alt'; 2993 } 2994 if ($this->inlineImageExists()) { 2995 $type[] = 'inline'; 2996 } 2997 if ($this->attachmentExists()) { 2998 $type[] = 'attach'; 2999 } 3000 $this->message_type = implode('_', $type); 3001 if ('' === $this->message_type) { 3002 //The 'plain' message_type refers to the message having a single body element, not that it is plain-text 3003 $this->message_type = 'plain'; 3004 } 3005 } 3006 3007 /** 3008 * Format a header line. 3009 * 3010 * @param string $name 3011 * @param string|int $value 3012 * 3013 * @return string 3014 */ 3015 public function headerLine($name, $value) 3016 { 3017 return $name . ': ' . $value . static::$LE; 3018 } 3019 3020 /** 3021 * Return a formatted mail line. 3022 * 3023 * @param string $value 3024 * 3025 * @return string 3026 */ 3027 public function textLine($value) 3028 { 3029 return $value . static::$LE; 3030 } 3031 3032 /** 3033 * Add an attachment from a path on the filesystem. 3034 * Never use a user-supplied path to a file! 3035 * Returns false if the file could not be found or read. 3036 * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client. 3037 * If you need to do that, fetch the resource yourself and pass it in via a local file or string. 3038 * 3039 * @param string $path Path to the attachment 3040 * @param string $name Overrides the attachment name 3041 * @param string $encoding File encoding (see $Encoding) 3042 * @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified 3043 * @param string $disposition Disposition to use 3044 * 3045 * @throws Exception 3046 * 3047 * @return bool 3048 */ 3049 public function addAttachment( 3050 $path, 3051 $name = '', 3052 $encoding = self::ENCODING_BASE64, 3053 $type = '', 3054 $disposition = 'attachment' 3055 ) { 3056 try { 3057 if (!static::fileIsAccessible($path)) { 3058 throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); 3059 } 3060 3061 //If a MIME type is not specified, try to work it out from the file name 3062 if ('' === $type) { 3063 $type = static::filenameToType($path); 3064 } 3065 3066 $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); 3067 if ('' === $name) { 3068 $name = $filename; 3069 } 3070 if (!$this->validateEncoding($encoding)) { 3071 throw new Exception($this->lang('encoding') . $encoding); 3072 } 3073 3074 $this->attachment[] = [ 3075 0 => $path, 3076 1 => $filename, 3077 2 => $name, 3078 3 => $encoding, 3079 4 => $type, 3080 5 => false, //isStringAttachment 3081 6 => $disposition, 3082 7 => $name, 3083 ]; 3084 } catch (Exception $exc) { 3085 $this->setError($exc->getMessage()); 3086 $this->edebug($exc->getMessage()); 3087 if ($this->exceptions) { 3088 throw $exc; 3089 } 3090 3091 return false; 3092 } 3093 3094 return true; 3095 } 3096 3097 /** 3098 * Return the array of attachments. 3099 * 3100 * @return array 3101 */ 3102 public function getAttachments() 3103 { 3104 return $this->attachment; 3105 } 3106 3107 /** 3108 * Attach all file, string, and binary attachments to the message. 3109 * Returns an empty string on failure. 3110 * 3111 * @param string $disposition_type 3112 * @param string $boundary 3113 * 3114 * @throws Exception 3115 * 3116 * @return string 3117 */ 3118 protected function attachAll($disposition_type, $boundary) 3119 { 3120 //Return text of body 3121 $mime = []; 3122 $cidUniq = []; 3123 $incl = []; 3124 3125 //Add all attachments 3126 foreach ($this->attachment as $attachment) { 3127 //Check if it is a valid disposition_filter 3128 if ($attachment[6] === $disposition_type) { 3129 //Check for string attachment 3130 $string = ''; 3131 $path = ''; 3132 $bString = $attachment[5]; 3133 if ($bString) { 3134 $string = $attachment[0]; 3135 } else { 3136 $path = $attachment[0]; 3137 } 3138 3139 $inclhash = hash('sha256', serialize($attachment)); 3140 if (in_array($inclhash, $incl, true)) { 3141 continue; 3142 } 3143 $incl[] = $inclhash; 3144 $name = $attachment[2]; 3145 $encoding = $attachment[3]; 3146 $type = $attachment[4]; 3147 $disposition = $attachment[6]; 3148 $cid = $attachment[7]; 3149 if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) { 3150 continue; 3151 } 3152 $cidUniq[$cid] = true; 3153 3154 $mime[] = sprintf('--%s%s', $boundary, static::$LE); 3155 //Only include a filename property if we have one 3156 if (!empty($name)) { 3157 $mime[] = sprintf( 3158 'Content-Type: %s; name=%s%s', 3159 $type, 3160 static::quotedString($this->encodeHeader($this->secureHeader($name))), 3161 static::$LE 3162 ); 3163 } else { 3164 $mime[] = sprintf( 3165 'Content-Type: %s%s', 3166 $type, 3167 static::$LE 3168 ); 3169 } 3170 //RFC1341 part 5 says 7bit is assumed if not specified 3171 if (static::ENCODING_7BIT !== $encoding) { 3172 $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE); 3173 } 3174 3175 //Only set Content-IDs on inline attachments 3176 if ((string) $cid !== '' && $disposition === 'inline') { 3177 $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE; 3178 } 3179 3180 //Allow for bypassing the Content-Disposition header 3181 if (!empty($disposition)) { 3182 $encoded_name = $this->encodeHeader($this->secureHeader($name)); 3183 if (!empty($encoded_name)) { 3184 $mime[] = sprintf( 3185 'Content-Disposition: %s; filename=%s%s', 3186 $disposition, 3187 static::quotedString($encoded_name), 3188 static::$LE . static::$LE 3189 ); 3190 } else { 3191 $mime[] = sprintf( 3192 'Content-Disposition: %s%s', 3193 $disposition, 3194 static::$LE . static::$LE 3195 ); 3196 } 3197 } else { 3198 $mime[] = static::$LE; 3199 } 3200 3201 //Encode as string attachment 3202 if ($bString) { 3203 $mime[] = $this->encodeString($string, $encoding); 3204 } else { 3205 $mime[] = $this->encodeFile($path, $encoding); 3206 } 3207 if ($this->isError()) { 3208 return ''; 3209 } 3210 $mime[] = static::$LE; 3211 } 3212 } 3213 3214 $mime[] = sprintf('--%s--%s', $boundary, static::$LE); 3215 3216 return implode('', $mime); 3217 } 3218 3219 /** 3220 * Encode a file attachment in requested format. 3221 * Returns an empty string on failure. 3222 * 3223 * @param string $path The full path to the file 3224 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' 3225 * 3226 * @return string 3227 */ 3228 protected function encodeFile($path, $encoding = self::ENCODING_BASE64) 3229 { 3230 try { 3231 if (!static::fileIsAccessible($path)) { 3232 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); 3233 } 3234 $file_buffer = file_get_contents($path); 3235 if (false === $file_buffer) { 3236 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); 3237 } 3238 $file_buffer = $this->encodeString($file_buffer, $encoding); 3239 3240 return $file_buffer; 3241 } catch (Exception $exc) { 3242 $this->setError($exc->getMessage()); 3243 $this->edebug($exc->getMessage()); 3244 if ($this->exceptions) { 3245 throw $exc; 3246 } 3247 3248 return ''; 3249 } 3250 } 3251 3252 /** 3253 * Encode a string in requested format. 3254 * Returns an empty string on failure. 3255 * 3256 * @param string $str The text to encode 3257 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' 3258 * 3259 * @throws Exception 3260 * 3261 * @return string 3262 */ 3263 public function encodeString($str, $encoding = self::ENCODING_BASE64) 3264 { 3265 $encoded = ''; 3266 switch (strtolower($encoding)) { 3267 case static::ENCODING_BASE64: 3268 $encoded = chunk_split( 3269 base64_encode($str), 3270 static::STD_LINE_LENGTH, 3271 static::$LE 3272 ); 3273 break; 3274 case static::ENCODING_7BIT: 3275 case static::ENCODING_8BIT: 3276 $encoded = static::normalizeBreaks($str); 3277 //Make sure it ends with a line break 3278 if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) { 3279 $encoded .= static::$LE; 3280 } 3281 break; 3282 case static::ENCODING_BINARY: 3283 $encoded = $str; 3284 break; 3285 case static::ENCODING_QUOTED_PRINTABLE: 3286 $encoded = $this->encodeQP($str); 3287 break; 3288 default: 3289 $this->setError($this->lang('encoding') . $encoding); 3290 if ($this->exceptions) { 3291 throw new Exception($this->lang('encoding') . $encoding); 3292 } 3293 break; 3294 } 3295 3296 return $encoded; 3297 } 3298 3299 /** 3300 * Encode a header value (not including its label) optimally. 3301 * Picks shortest of Q, B, or none. Result includes folding if needed. 3302 * See RFC822 definitions for phrase, comment and text positions. 3303 * 3304 * @param string $str The header value to encode 3305 * @param string $position What context the string will be used in 3306 * 3307 * @return string 3308 */ 3309 public function encodeHeader($str, $position = 'text') 3310 { 3311 $matchcount = 0; 3312 switch (strtolower($position)) { 3313 case 'phrase': 3314 if (!preg_match('/[\200-\377]/', $str)) { 3315 //Can't use addslashes as we don't know the value of magic_quotes_sybase 3316 $encoded = addcslashes($str, "\0..\37\177\\\""); 3317 if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { 3318 return $encoded; 3319 } 3320 3321 return "\"$encoded\""; 3322 } 3323 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); 3324 break; 3325 /* @noinspection PhpMissingBreakStatementInspection */ 3326 case 'comment': 3327 $matchcount = preg_match_all('/[()"]/', $str, $matches); 3328 //fallthrough 3329 case 'text': 3330 default: 3331 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); 3332 break; 3333 } 3334 3335 if ($this->has8bitChars($str)) { 3336 $charset = $this->CharSet; 3337 } else { 3338 $charset = static::CHARSET_ASCII; 3339 } 3340 3341 //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`"). 3342 $overhead = 8 + strlen($charset); 3343 3344 if ('mail' === $this->Mailer) { 3345 $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead; 3346 } else { 3347 $maxlen = static::MAX_LINE_LENGTH - $overhead; 3348 } 3349 3350 //Select the encoding that produces the shortest output and/or prevents corruption. 3351 if ($matchcount > strlen($str) / 3) { 3352 //More than 1/3 of the content needs encoding, use B-encode. 3353 $encoding = 'B'; 3354 } elseif ($matchcount > 0) { 3355 //Less than 1/3 of the content needs encoding, use Q-encode. 3356 $encoding = 'Q'; 3357 } elseif (strlen($str) > $maxlen) { 3358 //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption. 3359 $encoding = 'Q'; 3360 } else { 3361 //No reformatting needed 3362 $encoding = false; 3363 } 3364 3365 switch ($encoding) { 3366 case 'B': 3367 if ($this->hasMultiBytes($str)) { 3368 //Use a custom function which correctly encodes and wraps long 3369 //multibyte strings without breaking lines within a character 3370 $encoded = $this->base64EncodeWrapMB($str, "\n"); 3371 } else { 3372 $encoded = base64_encode($str); 3373 $maxlen -= $maxlen % 4; 3374 $encoded = trim(chunk_split($encoded, $maxlen, "\n")); 3375 } 3376 $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); 3377 break; 3378 case 'Q': 3379 $encoded = $this->encodeQ($str, $position); 3380 $encoded = $this->wrapText($encoded, $maxlen, true); 3381 $encoded = str_replace('=' . static::$LE, "\n", trim($encoded)); 3382 $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); 3383 break; 3384 default: 3385 return $str; 3386 } 3387 3388 return trim(static::normalizeBreaks($encoded)); 3389 } 3390 3391 /** 3392 * Check if a string contains multi-byte characters. 3393 * 3394 * @param string $str multi-byte text to wrap encode 3395 * 3396 * @return bool 3397 */ 3398 public function hasMultiBytes($str) 3399 { 3400 if (function_exists('mb_strlen')) { 3401 return strlen($str) > mb_strlen($str, $this->CharSet); 3402 } 3403 3404 //Assume no multibytes (we can't handle without mbstring functions anyway) 3405 return false; 3406 } 3407 3408 /** 3409 * Does a string contain any 8-bit chars (in any charset)? 3410 * 3411 * @param string $text 3412 * 3413 * @return bool 3414 */ 3415 public function has8bitChars($text) 3416 { 3417 return (bool) preg_match('/[\x80-\xFF]/', $text); 3418 } 3419 3420 /** 3421 * Encode and wrap long multibyte strings for mail headers 3422 * without breaking lines within a character. 3423 * Adapted from a function by paravoid. 3424 * 3425 * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 3426 * 3427 * @param string $str multi-byte text to wrap encode 3428 * @param string $linebreak string to use as linefeed/end-of-line 3429 * 3430 * @return string 3431 */ 3432 public function base64EncodeWrapMB($str, $linebreak = null) 3433 { 3434 $start = '=?' . $this->CharSet . '?B?'; 3435 $end = '?='; 3436 $encoded = ''; 3437 if (null === $linebreak) { 3438 $linebreak = static::$LE; 3439 } 3440 3441 $mb_length = mb_strlen($str, $this->CharSet); 3442 //Each line must have length <= 75, including $start and $end 3443 $length = 75 - strlen($start) - strlen($end); 3444 //Average multi-byte ratio 3445 $ratio = $mb_length / strlen($str); 3446 //Base64 has a 4:3 ratio 3447 $avgLength = floor($length * $ratio * .75); 3448 3449 $offset = 0; 3450 for ($i = 0; $i < $mb_length; $i += $offset) { 3451 $lookBack = 0; 3452 do { 3453 $offset = $avgLength - $lookBack; 3454 $chunk = mb_substr($str, $i, $offset, $this->CharSet); 3455 $chunk = base64_encode($chunk); 3456 ++$lookBack; 3457 } while (strlen($chunk) > $length); 3458 $encoded .= $chunk . $linebreak; 3459 } 3460 3461 //Chomp the last linefeed 3462 return substr($encoded, 0, -strlen($linebreak)); 3463 } 3464 3465 /** 3466 * Encode a string in quoted-printable format. 3467 * According to RFC2045 section 6.7. 3468 * 3469 * @param string $string The text to encode 3470 * 3471 * @return string 3472 */ 3473 public function encodeQP($string) 3474 { 3475 return static::normalizeBreaks(quoted_printable_encode($string)); 3476 } 3477 3478 /** 3479 * Encode a string using Q encoding. 3480 * 3481 * @see http://tools.ietf.org/html/rfc2047#section-4.2 3482 * 3483 * @param string $str the text to encode 3484 * @param string $position Where the text is going to be used, see the RFC for what that means 3485 * 3486 * @return string 3487 */ 3488 public function encodeQ($str, $position = 'text') 3489 { 3490 //There should not be any EOL in the string 3491 $pattern = ''; 3492 $encoded = str_replace(["\r", "\n"], '', $str); 3493 switch (strtolower($position)) { 3494 case 'phrase': 3495 //RFC 2047 section 5.3 3496 $pattern = '^A-Za-z0-9!*+\/ -'; 3497 break; 3498 /* 3499 * RFC 2047 section 5.2. 3500 * Build $pattern without including delimiters and [] 3501 */ 3502 /* @noinspection PhpMissingBreakStatementInspection */ 3503 case 'comment': 3504 $pattern = '\(\)"'; 3505 /* Intentional fall through */ 3506 case 'text': 3507 default: 3508 //RFC 2047 section 5.1 3509 //Replace every high ascii, control, =, ? and _ characters 3510 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; 3511 break; 3512 } 3513 $matches = []; 3514 if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { 3515 //If the string contains an '=', make sure it's the first thing we replace 3516 //so as to avoid double-encoding 3517 $eqkey = array_search('=', $matches[0], true); 3518 if (false !== $eqkey) { 3519 unset($matches[0][$eqkey]); 3520 array_unshift($matches[0], '='); 3521 } 3522 foreach (array_unique($matches[0]) as $char) { 3523 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); 3524 } 3525 } 3526 //Replace spaces with _ (more readable than =20) 3527 //RFC 2047 section 4.2(2) 3528 return str_replace(' ', '_', $encoded); 3529 } 3530 3531 /** 3532 * Add a string or binary attachment (non-filesystem). 3533 * This method can be used to attach ascii or binary data, 3534 * such as a BLOB record from a database. 3535 * 3536 * @param string $string String attachment data 3537 * @param string $filename Name of the attachment 3538 * @param string $encoding File encoding (see $Encoding) 3539 * @param string $type File extension (MIME) type 3540 * @param string $disposition Disposition to use 3541 * 3542 * @throws Exception 3543 * 3544 * @return bool True on successfully adding an attachment 3545 */ 3546 public function addStringAttachment( 3547 $string, 3548 $filename, 3549 $encoding = self::ENCODING_BASE64, 3550 $type = '', 3551 $disposition = 'attachment' 3552 ) { 3553 try { 3554 //If a MIME type is not specified, try to work it out from the file name 3555 if ('' === $type) { 3556 $type = static::filenameToType($filename); 3557 } 3558 3559 if (!$this->validateEncoding($encoding)) { 3560 throw new Exception($this->lang('encoding') . $encoding); 3561 } 3562 3563 //Append to $attachment array 3564 $this->attachment[] = [ 3565 0 => $string, 3566 1 => $filename, 3567 2 => static::mb_pathinfo($filename, PATHINFO_BASENAME), 3568 3 => $encoding, 3569 4 => $type, 3570 5 => true, //isStringAttachment 3571 6 => $disposition, 3572 7 => 0, 3573 ]; 3574 } catch (Exception $exc) { 3575 $this->setError($exc->getMessage()); 3576 $this->edebug($exc->getMessage()); 3577 if ($this->exceptions) { 3578 throw $exc; 3579 } 3580 3581 return false; 3582 } 3583 3584 return true; 3585 } 3586 3587 /** 3588 * Add an embedded (inline) attachment from a file. 3589 * This can include images, sounds, and just about any other document type. 3590 * These differ from 'regular' attachments in that they are intended to be 3591 * displayed inline with the message, not just attached for download. 3592 * This is used in HTML messages that embed the images 3593 * the HTML refers to using the $cid value. 3594 * Never use a user-supplied path to a file! 3595 * 3596 * @param string $path Path to the attachment 3597 * @param string $cid Content ID of the attachment; Use this to reference 3598 * the content when using an embedded image in HTML 3599 * @param string $name Overrides the attachment name 3600 * @param string $encoding File encoding (see $Encoding) 3601 * @param string $type File MIME type 3602 * @param string $disposition Disposition to use 3603 * 3604 * @throws Exception 3605 * 3606 * @return bool True on successfully adding an attachment 3607 */ 3608 public function addEmbeddedImage( 3609 $path, 3610 $cid, 3611 $name = '', 3612 $encoding = self::ENCODING_BASE64, 3613 $type = '', 3614 $disposition = 'inline' 3615 ) { 3616 try { 3617 if (!static::fileIsAccessible($path)) { 3618 throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); 3619 } 3620 3621 //If a MIME type is not specified, try to work it out from the file name 3622 if ('' === $type) { 3623 $type = static::filenameToType($path); 3624 } 3625 3626 if (!$this->validateEncoding($encoding)) { 3627 throw new Exception($this->lang('encoding') . $encoding); 3628 } 3629 3630 $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); 3631 if ('' === $name) { 3632 $name = $filename; 3633 } 3634 3635 //Append to $attachment array 3636 $this->attachment[] = [ 3637 0 => $path, 3638 1 => $filename, 3639 2 => $name, 3640 3 => $encoding, 3641 4 => $type, 3642 5 => false, //isStringAttachment 3643 6 => $disposition, 3644 7 => $cid, 3645 ]; 3646 } catch (Exception $exc) { 3647 $this->setError($exc->getMessage()); 3648 $this->edebug($exc->getMessage()); 3649 if ($this->exceptions) { 3650 throw $exc; 3651 } 3652 3653 return false; 3654 } 3655 3656 return true; 3657 } 3658 3659 /** 3660 * Add an embedded stringified attachment. 3661 * This can include images, sounds, and just about any other document type. 3662 * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type. 3663 * 3664 * @param string $string The attachment binary data 3665 * @param string $cid Content ID of the attachment; Use this to reference 3666 * the content when using an embedded image in HTML 3667 * @param string $name A filename for the attachment. If this contains an extension, 3668 * PHPMailer will attempt to set a MIME type for the attachment. 3669 * For example 'file.jpg' would get an 'image/jpeg' MIME type. 3670 * @param string $encoding File encoding (see $Encoding), defaults to 'base64' 3671 * @param string $type MIME type - will be used in preference to any automatically derived type 3672 * @param string $disposition Disposition to use 3673 * 3674 * @throws Exception 3675 * 3676 * @return bool True on successfully adding an attachment 3677 */ 3678 public function addStringEmbeddedImage( 3679 $string, 3680 $cid, 3681 $name = '', 3682 $encoding = self::ENCODING_BASE64, 3683 $type = '', 3684 $disposition = 'inline' 3685 ) { 3686 try { 3687 //If a MIME type is not specified, try to work it out from the name 3688 if ('' === $type && !empty($name)) { 3689 $type = static::filenameToType($name); 3690 } 3691 3692 if (!$this->validateEncoding($encoding)) { 3693 throw new Exception($this->lang('encoding') . $encoding); 3694 } 3695 3696 //Append to $attachment array 3697 $this->attachment[] = [ 3698 0 => $string, 3699 1 => $name, 3700 2 => $name, 3701 3 => $encoding, 3702 4 => $type, 3703 5 => true, //isStringAttachment 3704 6 => $disposition, 3705 7 => $cid, 3706 ]; 3707 } catch (Exception $exc) { 3708 $this->setError($exc->getMessage()); 3709 $this->edebug($exc->getMessage()); 3710 if ($this->exceptions) { 3711 throw $exc; 3712 } 3713 3714 return false; 3715 } 3716 3717 return true; 3718 } 3719 3720 /** 3721 * Validate encodings. 3722 * 3723 * @param string $encoding 3724 * 3725 * @return bool 3726 */ 3727 protected function validateEncoding($encoding) 3728 { 3729 return in_array( 3730 $encoding, 3731 [ 3732 self::ENCODING_7BIT, 3733 self::ENCODING_QUOTED_PRINTABLE, 3734 self::ENCODING_BASE64, 3735 self::ENCODING_8BIT, 3736 self::ENCODING_BINARY, 3737 ], 3738 true 3739 ); 3740 } 3741 3742 /** 3743 * Check if an embedded attachment is present with this cid. 3744 * 3745 * @param string $cid 3746 * 3747 * @return bool 3748 */ 3749 protected function cidExists($cid) 3750 { 3751 foreach ($this->attachment as $attachment) { 3752 if ('inline' === $attachment[6] && $cid === $attachment[7]) { 3753 return true; 3754 } 3755 } 3756 3757 return false; 3758 } 3759 3760 /** 3761 * Check if an inline attachment is present. 3762 * 3763 * @return bool 3764 */ 3765 public function inlineImageExists() 3766 { 3767 foreach ($this->attachment as $attachment) { 3768 if ('inline' === $attachment[6]) { 3769 return true; 3770 } 3771 } 3772 3773 return false; 3774 } 3775 3776 /** 3777 * Check if an attachment (non-inline) is present. 3778 * 3779 * @return bool 3780 */ 3781 public function attachmentExists() 3782 { 3783 foreach ($this->attachment as $attachment) { 3784 if ('attachment' === $attachment[6]) { 3785 return true; 3786 } 3787 } 3788 3789 return false; 3790 } 3791 3792 /** 3793 * Check if this message has an alternative body set. 3794 * 3795 * @return bool 3796 */ 3797 public function alternativeExists() 3798 { 3799 return !empty($this->AltBody); 3800 } 3801 3802 /** 3803 * Clear queued addresses of given kind. 3804 * 3805 * @param string $kind 'to', 'cc', or 'bcc' 3806 */ 3807 public function clearQueuedAddresses($kind) 3808 { 3809 $this->RecipientsQueue = array_filter( 3810 $this->RecipientsQueue, 3811 static function ($params) use ($kind) { 3812 return $params[0] !== $kind; 3813 } 3814 ); 3815 } 3816 3817 /** 3818 * Clear all To recipients. 3819 */ 3820 public function clearAddresses() 3821 { 3822 foreach ($this->to as $to) { 3823 unset($this->all_recipients[strtolower($to[0])]); 3824 } 3825 $this->to = []; 3826 $this->clearQueuedAddresses('to'); 3827 } 3828 3829 /** 3830 * Clear all CC recipients. 3831 */ 3832 public function clearCCs() 3833 { 3834 foreach ($this->cc as $cc) { 3835 unset($this->all_recipients[strtolower($cc[0])]); 3836 } 3837 $this->cc = []; 3838 $this->clearQueuedAddresses('cc'); 3839 } 3840 3841 /** 3842 * Clear all BCC recipients. 3843 */ 3844 public function clearBCCs() 3845 { 3846 foreach ($this->bcc as $bcc) { 3847 unset($this->all_recipients[strtolower($bcc[0])]); 3848 } 3849 $this->bcc = []; 3850 $this->clearQueuedAddresses('bcc'); 3851 } 3852 3853 /** 3854 * Clear all ReplyTo recipients. 3855 */ 3856 public function clearReplyTos() 3857 { 3858 $this->ReplyTo = []; 3859 $this->ReplyToQueue = []; 3860 } 3861 3862 /** 3863 * Clear all recipient types. 3864 */ 3865 public function clearAllRecipients() 3866 { 3867 $this->to = []; 3868 $this->cc = []; 3869 $this->bcc = []; 3870 $this->all_recipients = []; 3871 $this->RecipientsQueue = []; 3872 } 3873 3874 /** 3875 * Clear all filesystem, string, and binary attachments. 3876 */ 3877 public function clearAttachments() 3878 { 3879 $this->attachment = []; 3880 } 3881 3882 /** 3883 * Clear all custom headers. 3884 */ 3885 public function clearCustomHeaders() 3886 { 3887 $this->CustomHeader = []; 3888 } 3889 3890 /** 3891 * Add an error message to the error container. 3892 * 3893 * @param string $msg 3894 */ 3895 protected function setError($msg) 3896 { 3897 ++$this->error_count; 3898 if ('smtp' === $this->Mailer && null !== $this->smtp) { 3899 $lasterror = $this->smtp->getError(); 3900 if (!empty($lasterror['error'])) { 3901 $msg .= $this->lang('smtp_error') . $lasterror['error']; 3902 if (!empty($lasterror['detail'])) { 3903 $msg .= ' Detail: ' . $lasterror['detail']; 3904 } 3905 if (!empty($lasterror['smtp_code'])) { 3906 $msg .= ' SMTP code: ' . $lasterror['smtp_code']; 3907 } 3908 if (!empty($lasterror['smtp_code_ex'])) { 3909 $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex']; 3910 } 3911 } 3912 } 3913 $this->ErrorInfo = $msg; 3914 } 3915 3916 /** 3917 * Return an RFC 822 formatted date. 3918 * 3919 * @return string 3920 */ 3921 public static function rfcDate() 3922 { 3923 //Set the time zone to whatever the default is to avoid 500 errors 3924 //Will default to UTC if it's not set properly in php.ini 3925 date_default_timezone_set(@date_default_timezone_get()); 3926 3927 return date('D, j M Y H:i:s O'); 3928 } 3929 3930 /** 3931 * Get the server hostname. 3932 * Returns 'localhost.localdomain' if unknown. 3933 * 3934 * @return string 3935 */ 3936 protected function serverHostname() 3937 { 3938 $result = ''; 3939 if (!empty($this->Hostname)) { 3940 $result = $this->Hostname; 3941 } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) { 3942 $result = $_SERVER['SERVER_NAME']; 3943 } elseif (function_exists('gethostname') && gethostname() !== false) { 3944 $result = gethostname(); 3945 } elseif (php_uname('n') !== false) { 3946 $result = php_uname('n'); 3947 } 3948 if (!static::isValidHost($result)) { 3949 return 'localhost.localdomain'; 3950 } 3951 3952 return $result; 3953 } 3954 3955 /** 3956 * Validate whether a string contains a valid value to use as a hostname or IP address. 3957 * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`. 3958 * 3959 * @param string $host The host name or IP address to check 3960 * 3961 * @return bool 3962 */ 3963 public static function isValidHost($host) 3964 { 3965 //Simple syntax limits 3966 if ( 3967 empty($host) 3968 || !is_string($host) 3969 || strlen($host) > 256 3970 || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+])$/', $host) 3971 ) { 3972 return false; 3973 } 3974 //Looks like a bracketed IPv6 address 3975 if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') { 3976 return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; 3977 } 3978 //If removing all the dots results in a numeric string, it must be an IPv4 address. 3979 //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names 3980 if (is_numeric(str_replace('.', '', $host))) { 3981 //Is it a valid IPv4 address? 3982 return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; 3983 } 3984 if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) { 3985 //Is it a syntactically valid hostname? 3986 return true; 3987 } 3988 3989 return false; 3990 } 3991 3992 /** 3993 * Get an error message in the current language. 3994 * 3995 * @param string $key 3996 * 3997 * @return string 3998 */ 3999 protected function lang($key) 4000 { 4001 if (count($this->language) < 1) { 4002 $this->setLanguage(); //Set the default language 4003 } 4004 4005 if (array_key_exists($key, $this->language)) { 4006 if ('smtp_connect_failed' === $key) { 4007 //Include a link to troubleshooting docs on SMTP connection failure. 4008 //This is by far the biggest cause of support questions 4009 //but it's usually not PHPMailer's fault. 4010 return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; 4011 } 4012 4013 return $this->language[$key]; 4014 } 4015 4016 //Return the key as a fallback 4017 return $key; 4018 } 4019 4020 /** 4021 * Check if an error occurred. 4022 * 4023 * @return bool True if an error did occur 4024 */ 4025 public function isError() 4026 { 4027 return $this->error_count > 0; 4028 } 4029 4030 /** 4031 * Add a custom header. 4032 * $name value can be overloaded to contain 4033 * both header name and value (name:value). 4034 * 4035 * @param string $name Custom header name 4036 * @param string|null $value Header value 4037 * 4038 * @throws Exception 4039 */ 4040 public function addCustomHeader($name, $value = null) 4041 { 4042 if (null === $value && strpos($name, ':') !== false) { 4043 //Value passed in as name:value 4044 list($name, $value) = explode(':', $name, 2); 4045 } 4046 $name = trim($name); 4047 $value = trim($value); 4048 //Ensure name is not empty, and that neither name nor value contain line breaks 4049 if (empty($name) || strpbrk($name . $value, "\r\n") !== false) { 4050 if ($this->exceptions) { 4051 throw new Exception('Invalid header name or value'); 4052 } 4053 4054 return false; 4055 } 4056 $this->CustomHeader[] = [$name, $value]; 4057 4058 return true; 4059 } 4060 4061 /** 4062 * Returns all custom headers. 4063 * 4064 * @return array 4065 */ 4066 public function getCustomHeaders() 4067 { 4068 return $this->CustomHeader; 4069 } 4070 4071 /** 4072 * Create a message body from an HTML string. 4073 * Automatically inlines images and creates a plain-text version by converting the HTML, 4074 * overwriting any existing values in Body and AltBody. 4075 * Do not source $message content from user input! 4076 * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty 4077 * will look for an image file in $basedir/images/a.png and convert it to inline. 4078 * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) 4079 * Converts data-uri images into embedded attachments. 4080 * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. 4081 * 4082 * @param string $message HTML message string 4083 * @param string $basedir Absolute path to a base directory to prepend to relative paths to images 4084 * @param bool|callable $advanced Whether to use the internal HTML to text converter 4085 * or your own custom converter 4086 * @return string The transformed message body 4087 * 4088 * @throws Exception 4089 * 4090 * @see PHPMailer::html2text() 4091 */ 4092 public function msgHTML($message, $basedir = '', $advanced = false) 4093 { 4094 preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images); 4095 if (array_key_exists(2, $images)) { 4096 if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { 4097 //Ensure $basedir has a trailing / 4098 $basedir .= '/'; 4099 } 4100 foreach ($images[2] as $imgindex => $url) { 4101 //Convert data URIs into embedded images 4102 //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" 4103 $match = []; 4104 if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) { 4105 if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) { 4106 $data = base64_decode($match[3]); 4107 } elseif ('' === $match[2]) { 4108 $data = rawurldecode($match[3]); 4109 } else { 4110 //Not recognised so leave it alone 4111 continue; 4112 } 4113 //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places 4114 //will only be embedded once, even if it used a different encoding 4115 $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2 4116 4117 if (!$this->cidExists($cid)) { 4118 $this->addStringEmbeddedImage( 4119 $data, 4120 $cid, 4121 'embed' . $imgindex, 4122 static::ENCODING_BASE64, 4123 $match[1] 4124 ); 4125 } 4126 $message = str_replace( 4127 $images[0][$imgindex], 4128 $images[1][$imgindex] . '="cid:' . $cid . '"', 4129 $message 4130 ); 4131 continue; 4132 } 4133 if ( 4134 //Only process relative URLs if a basedir is provided (i.e. no absolute local paths) 4135 !empty($basedir) 4136 //Ignore URLs containing parent dir traversal (..) 4137 && (strpos($url, '..') === false) 4138 //Do not change urls that are already inline images 4139 && 0 !== strpos($url, 'cid:') 4140 //Do not change absolute URLs, including anonymous protocol 4141 && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) 4142 ) { 4143 $filename = static::mb_pathinfo($url, PATHINFO_BASENAME); 4144 $directory = dirname($url); 4145 if ('.' === $directory) { 4146 $directory = ''; 4147 } 4148 //RFC2392 S 2 4149 $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0'; 4150 if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { 4151 $basedir .= '/'; 4152 } 4153 if (strlen($directory) > 1 && '/' !== substr($directory, -1)) { 4154 $directory .= '/'; 4155 } 4156 if ( 4157 $this->addEmbeddedImage( 4158 $basedir . $directory . $filename, 4159 $cid, 4160 $filename, 4161 static::ENCODING_BASE64, 4162 static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION)) 4163 ) 4164 ) { 4165 $message = preg_replace( 4166 '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', 4167 $images[1][$imgindex] . '="cid:' . $cid . '"', 4168 $message 4169 ); 4170 } 4171 } 4172 } 4173 } 4174 $this->isHTML(); 4175 //Convert all message body line breaks to LE, makes quoted-printable encoding work much better 4176 $this->Body = static::normalizeBreaks($message); 4177 $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced)); 4178 if (!$this->alternativeExists()) { 4179 $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.' 4180 . static::$LE; 4181 } 4182 4183 return $this->Body; 4184 } 4185 4186 /** 4187 * Convert an HTML string into plain text. 4188 * This is used by msgHTML(). 4189 * Note - older versions of this function used a bundled advanced converter 4190 * which was removed for license reasons in #232. 4191 * Example usage: 4192 * 4193 * ```php 4194 * //Use default conversion 4195 * $plain = $mail->html2text($html); 4196 * //Use your own custom converter 4197 * $plain = $mail->html2text($html, function($html) { 4198 * $converter = new MyHtml2text($html); 4199 * return $converter->get_text(); 4200 * }); 4201 * ``` 4202 * 4203 * @param string $html The HTML text to convert 4204 * @param bool|callable $advanced Any boolean value to use the internal converter, 4205 * or provide your own callable for custom conversion 4206 * 4207 * @return string 4208 */ 4209 public function html2text($html, $advanced = false) 4210 { 4211 if (is_callable($advanced)) { 4212 return call_user_func($advanced, $html); 4213 } 4214 4215 return html_entity_decode( 4216 trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), 4217 ENT_QUOTES, 4218 $this->CharSet 4219 ); 4220 } 4221 4222 /** 4223 * Get the MIME type for a file extension. 4224 * 4225 * @param string $ext File extension 4226 * 4227 * @return string MIME type of file 4228 */ 4229 public static function _mime_types($ext = '') 4230 { 4231 $mimes = [ 4232 'xl' => 'application/excel', 4233 'js' => 'application/javascript', 4234 'hqx' => 'application/mac-binhex40', 4235 'cpt' => 'application/mac-compactpro', 4236 'bin' => 'application/macbinary', 4237 'doc' => 'application/msword', 4238 'word' => 'application/msword', 4239 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 4240 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 4241 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 4242 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 4243 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 4244 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 4245 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 4246 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 4247 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', 4248 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 4249 'class' => 'application/octet-stream', 4250 'dll' => 'application/octet-stream', 4251 'dms' => 'application/octet-stream', 4252 'exe' => 'application/octet-stream', 4253 'lha' => 'application/octet-stream', 4254 'lzh' => 'application/octet-stream', 4255 'psd' => 'application/octet-stream', 4256 'sea' => 'application/octet-stream', 4257 'so' => 'application/octet-stream', 4258 'oda' => 'application/oda', 4259 'pdf' => 'application/pdf', 4260 'ai' => 'application/postscript', 4261 'eps' => 'application/postscript', 4262 'ps' => 'application/postscript', 4263 'smi' => 'application/smil', 4264 'smil' => 'application/smil', 4265 'mif' => 'application/vnd.mif', 4266 'xls' => 'application/vnd.ms-excel', 4267 'ppt' => 'application/vnd.ms-powerpoint', 4268 'wbxml' => 'application/vnd.wap.wbxml', 4269 'wmlc' => 'application/vnd.wap.wmlc', 4270 'dcr' => 'application/x-director', 4271 'dir' => 'application/x-director', 4272 'dxr' => 'application/x-director', 4273 'dvi' => 'application/x-dvi', 4274 'gtar' => 'application/x-gtar', 4275 'php3' => 'application/x-httpd-php', 4276 'php4' => 'application/x-httpd-php', 4277 'php' => 'application/x-httpd-php', 4278 'phtml' => 'application/x-httpd-php', 4279 'phps' => 'application/x-httpd-php-source', 4280 'swf' => 'application/x-shockwave-flash', 4281 'sit' => 'application/x-stuffit', 4282 'tar' => 'application/x-tar', 4283 'tgz' => 'application/x-tar', 4284 'xht' => 'application/xhtml+xml', 4285 'xhtml' => 'application/xhtml+xml', 4286 'zip' => 'application/zip', 4287 'mid' => 'audio/midi', 4288 'midi' => 'audio/midi', 4289 'mp2' => 'audio/mpeg', 4290 'mp3' => 'audio/mpeg', 4291 'm4a' => 'audio/mp4', 4292 'mpga' => 'audio/mpeg', 4293 'aif' => 'audio/x-aiff', 4294 'aifc' => 'audio/x-aiff', 4295 'aiff' => 'audio/x-aiff', 4296 'ram' => 'audio/x-pn-realaudio', 4297 'rm' => 'audio/x-pn-realaudio', 4298 'rpm' => 'audio/x-pn-realaudio-plugin', 4299 'ra' => 'audio/x-realaudio', 4300 'wav' => 'audio/x-wav', 4301 'mka' => 'audio/x-matroska', 4302 'bmp' => 'image/bmp', 4303 'gif' => 'image/gif', 4304 'jpeg' => 'image/jpeg', 4305 'jpe' => 'image/jpeg', 4306 'jpg' => 'image/jpeg', 4307 'png' => 'image/png', 4308 'tiff' => 'image/tiff', 4309 'tif' => 'image/tiff', 4310 'webp' => 'image/webp', 4311 'avif' => 'image/avif', 4312 'heif' => 'image/heif', 4313 'heifs' => 'image/heif-sequence', 4314 'heic' => 'image/heic', 4315 'heics' => 'image/heic-sequence', 4316 'eml' => 'message/rfc822', 4317 'css' => 'text/css', 4318 'html' => 'text/html', 4319 'htm' => 'text/html', 4320 'shtml' => 'text/html', 4321 'log' => 'text/plain', 4322 'text' => 'text/plain', 4323 'txt' => 'text/plain', 4324 'rtx' => 'text/richtext', 4325 'rtf' => 'text/rtf', 4326 'vcf' => 'text/vcard', 4327 'vcard' => 'text/vcard', 4328 'ics' => 'text/calendar', 4329 'xml' => 'text/xml', 4330 'xsl' => 'text/xml', 4331 'wmv' => 'video/x-ms-wmv', 4332 'mpeg' => 'video/mpeg', 4333 'mpe' => 'video/mpeg', 4334 'mpg' => 'video/mpeg', 4335 'mp4' => 'video/mp4', 4336 'm4v' => 'video/mp4', 4337 'mov' => 'video/quicktime', 4338 'qt' => 'video/quicktime', 4339 'rv' => 'video/vnd.rn-realvideo', 4340 'avi' => 'video/x-msvideo', 4341 'movie' => 'video/x-sgi-movie', 4342 'webm' => 'video/webm', 4343 'mkv' => 'video/x-matroska', 4344 ]; 4345 $ext = strtolower($ext); 4346 if (array_key_exists($ext, $mimes)) { 4347 return $mimes[$ext]; 4348 } 4349 4350 return 'application/octet-stream'; 4351 } 4352 4353 /** 4354 * Map a file name to a MIME type. 4355 * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. 4356 * 4357 * @param string $filename A file name or full path, does not need to exist as a file 4358 * 4359 * @return string 4360 */ 4361 public static function filenameToType($filename) 4362 { 4363 //In case the path is a URL, strip any query string before getting extension 4364 $qpos = strpos($filename, '?'); 4365 if (false !== $qpos) { 4366 $filename = substr($filename, 0, $qpos); 4367 } 4368 $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION); 4369 4370 return static::_mime_types($ext); 4371 } 4372 4373 /** 4374 * Multi-byte-safe pathinfo replacement. 4375 * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe. 4376 * 4377 * @see http://www.php.net/manual/en/function.pathinfo.php#107461 4378 * 4379 * @param string $path A filename or path, does not need to exist as a file 4380 * @param int|string $options Either a PATHINFO_* constant, 4381 * or a string name to return only the specified piece 4382 * 4383 * @return string|array 4384 */ 4385 public static function mb_pathinfo($path, $options = null) 4386 { 4387 $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '']; 4388 $pathinfo = []; 4389 if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) { 4390 if (array_key_exists(1, $pathinfo)) { 4391 $ret['dirname'] = $pathinfo[1]; 4392 } 4393 if (array_key_exists(2, $pathinfo)) { 4394 $ret['basename'] = $pathinfo[2]; 4395 } 4396 if (array_key_exists(5, $pathinfo)) { 4397 $ret['extension'] = $pathinfo[5]; 4398 } 4399 if (array_key_exists(3, $pathinfo)) { 4400 $ret['filename'] = $pathinfo[3]; 4401 } 4402 } 4403 switch ($options) { 4404 case PATHINFO_DIRNAME: 4405 case 'dirname': 4406 return $ret['dirname']; 4407 case PATHINFO_BASENAME: 4408 case 'basename': 4409 return $ret['basename']; 4410 case PATHINFO_EXTENSION: 4411 case 'extension': 4412 return $ret['extension']; 4413 case PATHINFO_FILENAME: 4414 case 'filename': 4415 return $ret['filename']; 4416 default: 4417 return $ret; 4418 } 4419 } 4420 4421 /** 4422 * Set or reset instance properties. 4423 * You should avoid this function - it's more verbose, less efficient, more error-prone and 4424 * harder to debug than setting properties directly. 4425 * Usage Example: 4426 * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);` 4427 * is the same as: 4428 * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`. 4429 * 4430 * @param string $name The property name to set 4431 * @param mixed $value The value to set the property to 4432 * 4433 * @return bool 4434 */ 4435 public function set($name, $value = '') 4436 { 4437 if (property_exists($this, $name)) { 4438 $this->$name = $value; 4439 4440 return true; 4441 } 4442 $this->setError($this->lang('variable_set') . $name); 4443 4444 return false; 4445 } 4446 4447 /** 4448 * Strip newlines to prevent header injection. 4449 * 4450 * @param string $str 4451 * 4452 * @return string 4453 */ 4454 public function secureHeader($str) 4455 { 4456 return trim(str_replace(["\r", "\n"], '', $str)); 4457 } 4458 4459 /** 4460 * Normalize line breaks in a string. 4461 * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. 4462 * Defaults to CRLF (for message bodies) and preserves consecutive breaks. 4463 * 4464 * @param string $text 4465 * @param string $breaktype What kind of line break to use; defaults to static::$LE 4466 * 4467 * @return string 4468 */ 4469 public static function normalizeBreaks($text, $breaktype = null) 4470 { 4471 if (null === $breaktype) { 4472 $breaktype = static::$LE; 4473 } 4474 //Normalise to \n 4475 $text = str_replace([self::CRLF, "\r"], "\n", $text); 4476 //Now convert LE as needed 4477 if ("\n" !== $breaktype) { 4478 $text = str_replace("\n", $breaktype, $text); 4479 } 4480 4481 return $text; 4482 } 4483 4484 /** 4485 * Remove trailing breaks from a string. 4486 * 4487 * @param string $text 4488 * 4489 * @return string The text to remove breaks from 4490 */ 4491 public static function stripTrailingWSP($text) 4492 { 4493 return rtrim($text, " \r\n\t"); 4494 } 4495 4496 /** 4497 * Return the current line break format string. 4498 * 4499 * @return string 4500 */ 4501 public static function getLE() 4502 { 4503 return static::$LE; 4504 } 4505 4506 /** 4507 * Set the line break format string, e.g. "\r\n". 4508 * 4509 * @param string $le 4510 */ 4511 protected static function setLE($le) 4512 { 4513 static::$LE = $le; 4514 } 4515 4516 /** 4517 * Set the public and private key files and password for S/MIME signing. 4518 * 4519 * @param string $cert_filename 4520 * @param string $key_filename 4521 * @param string $key_pass Password for private key 4522 * @param string $extracerts_filename Optional path to chain certificate 4523 */ 4524 public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') 4525 { 4526 $this->sign_cert_file = $cert_filename; 4527 $this->sign_key_file = $key_filename; 4528 $this->sign_key_pass = $key_pass; 4529 $this->sign_extracerts_file = $extracerts_filename; 4530 } 4531 4532 /** 4533 * Quoted-Printable-encode a DKIM header. 4534 * 4535 * @param string $txt 4536 * 4537 * @return string 4538 */ 4539 public function DKIM_QP($txt) 4540 { 4541 $line = ''; 4542 $len = strlen($txt); 4543 for ($i = 0; $i < $len; ++$i) { 4544 $ord = ord($txt[$i]); 4545 if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { 4546 $line .= $txt[$i]; 4547 } else { 4548 $line .= '=' . sprintf('%02X', $ord); 4549 } 4550 } 4551 4552 return $line; 4553 } 4554 4555 /** 4556 * Generate a DKIM signature. 4557 * 4558 * @param string $signHeader 4559 * 4560 * @throws Exception 4561 * 4562 * @return string The DKIM signature value 4563 */ 4564 public function DKIM_Sign($signHeader) 4565 { 4566 if (!defined('PKCS7_TEXT')) { 4567 if ($this->exceptions) { 4568 throw new Exception($this->lang('extension_missing') . 'openssl'); 4569 } 4570 4571 return ''; 4572 } 4573 $privKeyStr = !empty($this->DKIM_private_string) ? 4574 $this->DKIM_private_string : 4575 file_get_contents($this->DKIM_private); 4576 if ('' !== $this->DKIM_passphrase) { 4577 $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); 4578 } else { 4579 $privKey = openssl_pkey_get_private($privKeyStr); 4580 } 4581 if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { 4582 if (\PHP_MAJOR_VERSION < 8) { 4583 openssl_pkey_free($privKey); 4584 } 4585 4586 return base64_encode($signature); 4587 } 4588 if (\PHP_MAJOR_VERSION < 8) { 4589 openssl_pkey_free($privKey); 4590 } 4591 4592 return ''; 4593 } 4594 4595 /** 4596 * Generate a DKIM canonicalization header. 4597 * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2. 4598 * Canonicalized headers should *always* use CRLF, regardless of mailer setting. 4599 * 4600 * @see https://tools.ietf.org/html/rfc6376#section-3.4.2 4601 * 4602 * @param string $signHeader Header 4603 * 4604 * @return string 4605 */ 4606 public function DKIM_HeaderC($signHeader) 4607 { 4608 //Normalize breaks to CRLF (regardless of the mailer) 4609 $signHeader = static::normalizeBreaks($signHeader, self::CRLF); 4610 //Unfold header lines 4611 //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]` 4612 //@see https://tools.ietf.org/html/rfc5322#section-2.2 4613 //That means this may break if you do something daft like put vertical tabs in your headers. 4614 $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader); 4615 //Break headers out into an array 4616 $lines = explode(self::CRLF, $signHeader); 4617 foreach ($lines as $key => $line) { 4618 //If the header is missing a :, skip it as it's invalid 4619 //This is likely to happen because the explode() above will also split 4620 //on the trailing LE, leaving an empty line 4621 if (strpos($line, ':') === false) { 4622 continue; 4623 } 4624 list($heading, $value) = explode(':', $line, 2); 4625 //Lower-case header name 4626 $heading = strtolower($heading); 4627 //Collapse white space within the value, also convert WSP to space 4628 $value = preg_replace('/[ \t]+/', ' ', $value); 4629 //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value 4630 //But then says to delete space before and after the colon. 4631 //Net result is the same as trimming both ends of the value. 4632 //By elimination, the same applies to the field name 4633 $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t"); 4634 } 4635 4636 return implode(self::CRLF, $lines); 4637 } 4638 4639 /** 4640 * Generate a DKIM canonicalization body. 4641 * Uses the 'simple' algorithm from RFC6376 section 3.4.3. 4642 * Canonicalized bodies should *always* use CRLF, regardless of mailer setting. 4643 * 4644 * @see https://tools.ietf.org/html/rfc6376#section-3.4.3 4645 * 4646 * @param string $body Message Body 4647 * 4648 * @return string 4649 */ 4650 public function DKIM_BodyC($body) 4651 { 4652 if (empty($body)) { 4653 return self::CRLF; 4654 } 4655 //Normalize line endings to CRLF 4656 $body = static::normalizeBreaks($body, self::CRLF); 4657 4658 //Reduce multiple trailing line breaks to a single one 4659 return static::stripTrailingWSP($body) . self::CRLF; 4660 } 4661 4662 /** 4663 * Create the DKIM header and body in a new message header. 4664 * 4665 * @param string $headers_line Header lines 4666 * @param string $subject Subject 4667 * @param string $body Body 4668 * 4669 * @throws Exception 4670 * 4671 * @return string 4672 */ 4673 public function DKIM_Add($headers_line, $subject, $body) 4674 { 4675 $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms 4676 $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body 4677 $DKIMquery = 'dns/txt'; //Query method 4678 $DKIMtime = time(); 4679 //Always sign these headers without being asked 4680 //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1 4681 $autoSignHeaders = [ 4682 'from', 4683 'to', 4684 'cc', 4685 'date', 4686 'subject', 4687 'reply-to', 4688 'message-id', 4689 'content-type', 4690 'mime-version', 4691 'x-mailer', 4692 ]; 4693 if (stripos($headers_line, 'Subject') === false) { 4694 $headers_line .= 'Subject: ' . $subject . static::$LE; 4695 } 4696 $headerLines = explode(static::$LE, $headers_line); 4697 $currentHeaderLabel = ''; 4698 $currentHeaderValue = ''; 4699 $parsedHeaders = []; 4700 $headerLineIndex = 0; 4701 $headerLineCount = count($headerLines); 4702 foreach ($headerLines as $headerLine) { 4703 $matches = []; 4704 if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) { 4705 if ($currentHeaderLabel !== '') { 4706 //We were previously in another header; This is the start of a new header, so save the previous one 4707 $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; 4708 } 4709 $currentHeaderLabel = $matches[1]; 4710 $currentHeaderValue = $matches[2]; 4711 } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) { 4712 //This is a folded continuation of the current header, so unfold it 4713 $currentHeaderValue .= ' ' . $matches[1]; 4714 } 4715 ++$headerLineIndex; 4716 if ($headerLineIndex >= $headerLineCount) { 4717 //This was the last line, so finish off this header 4718 $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; 4719 } 4720 } 4721 $copiedHeaders = []; 4722 $headersToSignKeys = []; 4723 $headersToSign = []; 4724 foreach ($parsedHeaders as $header) { 4725 //Is this header one that must be included in the DKIM signature? 4726 if (in_array(strtolower($header['label']), $autoSignHeaders, true)) { 4727 $headersToSignKeys[] = $header['label']; 4728 $headersToSign[] = $header['label'] . ': ' . $header['value']; 4729 if ($this->DKIM_copyHeaderFields) { 4730 $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC 4731 str_replace('|', '=7C', $this->DKIM_QP($header['value'])); 4732 } 4733 continue; 4734 } 4735 //Is this an extra custom header we've been asked to sign? 4736 if (in_array($header['label'], $this->DKIM_extraHeaders, true)) { 4737 //Find its value in custom headers 4738 foreach ($this->CustomHeader as $customHeader) { 4739 if ($customHeader[0] === $header['label']) { 4740 $headersToSignKeys[] = $header['label']; 4741 $headersToSign[] = $header['label'] . ': ' . $header['value']; 4742 if ($this->DKIM_copyHeaderFields) { 4743 $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC 4744 str_replace('|', '=7C', $this->DKIM_QP($header['value'])); 4745 } 4746 //Skip straight to the next header 4747 continue 2; 4748 } 4749 } 4750 } 4751 } 4752 $copiedHeaderFields = ''; 4753 if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) { 4754 //Assemble a DKIM 'z' tag 4755 $copiedHeaderFields = ' z='; 4756 $first = true; 4757 foreach ($copiedHeaders as $copiedHeader) { 4758 if (!$first) { 4759 $copiedHeaderFields .= static::$LE . ' |'; 4760 } 4761 //Fold long values 4762 if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) { 4763 $copiedHeaderFields .= substr( 4764 chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS), 4765 0, 4766 -strlen(static::$LE . self::FWS) 4767 ); 4768 } else { 4769 $copiedHeaderFields .= $copiedHeader; 4770 } 4771 $first = false; 4772 } 4773 $copiedHeaderFields .= ';' . static::$LE; 4774 } 4775 $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE; 4776 $headerValues = implode(static::$LE, $headersToSign); 4777 $body = $this->DKIM_BodyC($body); 4778 //Base64 of packed binary SHA-256 hash of body 4779 $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); 4780 $ident = ''; 4781 if ('' !== $this->DKIM_identity) { 4782 $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE; 4783 } 4784 //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag 4785 //which is appended after calculating the signature 4786 //https://tools.ietf.org/html/rfc6376#section-3.5 4787 $dkimSignatureHeader = 'DKIM-Signature: v=1;' . 4788 ' d=' . $this->DKIM_domain . ';' . 4789 ' s=' . $this->DKIM_selector . ';' . static::$LE . 4790 ' a=' . $DKIMsignatureType . ';' . 4791 ' q=' . $DKIMquery . ';' . 4792 ' t=' . $DKIMtime . ';' . 4793 ' c=' .