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