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 22namespace 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 */ 32class 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.1'; 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($domain, $errorcode, \INTL_IDNA_VARIANT_UTS46); 1455 } elseif (defined('INTL_IDNA_VARIANT_2003')) { 1456 //Fall back to this old, deprecated/removed encoding 1457 $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003); 1458 } else { 1459 //Fall back to a default we don't know about 1460 $punycode = idn_to_ascii($domain, $errorcode); 1461 } 1462 if (false !== $punycode) { 1463 return substr($address, 0, $pos) . $punycode; 1464 } 1465 } 1466 } 1467 1468 return $address; 1469 } 1470 1471 /** 1472 * Create a message and send it. 1473 * Uses the sending method specified by $Mailer. 1474 * 1475 * @throws Exception 1476 * 1477 * @return bool false on error - See the ErrorInfo property for details of the error 1478 */ 1479 public function send() 1480 { 1481 try { 1482 if (!$this->preSend()) { 1483 return false; 1484 } 1485 1486 return $this->postSend(); 1487 } catch (Exception $exc) { 1488 $this->mailHeader = ''; 1489 $this->setError($exc->getMessage()); 1490 if ($this->exceptions) { 1491 throw $exc; 1492 } 1493 1494 return false; 1495 } 1496 } 1497 1498 /** 1499 * Prepare a message for sending. 1500 * 1501 * @throws Exception 1502 * 1503 * @return bool 1504 */ 1505 public function preSend() 1506 { 1507 if ( 1508 'smtp' === $this->Mailer 1509 || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0)) 1510 ) { 1511 //SMTP mandates RFC-compliant line endings 1512 //and it's also used with mail() on Windows 1513 static::setLE(self::CRLF); 1514 } else { 1515 //Maintain backward compatibility with legacy Linux command line mailers 1516 static::setLE(PHP_EOL); 1517 } 1518 //Check for buggy PHP versions that add a header with an incorrect line break 1519 if ( 1520 'mail' === $this->Mailer 1521 && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017) 1522 || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103)) 1523 && ini_get('mail.add_x_header') === '1' 1524 && stripos(PHP_OS, 'WIN') === 0 1525 ) { 1526 trigger_error($this->lang('buggy_php'), E_USER_WARNING); 1527 } 1528 1529 try { 1530 $this->error_count = 0; //Reset errors 1531 $this->mailHeader = ''; 1532 1533 //Dequeue recipient and Reply-To addresses with IDN 1534 foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { 1535 $params[1] = $this->punyencodeAddress($params[1]); 1536 call_user_func_array([$this, 'addAnAddress'], $params); 1537 } 1538 if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { 1539 throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL); 1540 } 1541 1542 //Validate From, Sender, and ConfirmReadingTo addresses 1543 foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) { 1544 $this->$address_kind = trim($this->$address_kind); 1545 if (empty($this->$address_kind)) { 1546 continue; 1547 } 1548 $this->$address_kind = $this->punyencodeAddress($this->$address_kind); 1549 if (!static::validateAddress($this->$address_kind)) { 1550 $error_message = sprintf( 1551 '%s (%s): %s', 1552 $this->lang('invalid_address'), 1553 $address_kind, 1554 $this->$address_kind 1555 ); 1556 $this->setError($error_message); 1557 $this->edebug($error_message); 1558 if ($this->exceptions) { 1559 throw new Exception($error_message); 1560 } 1561 1562 return false; 1563 } 1564 } 1565 1566 //Set whether the message is multipart/alternative 1567 if ($this->alternativeExists()) { 1568 $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE; 1569 } 1570 1571 $this->setMessageType(); 1572 //Refuse to send an empty message unless we are specifically allowing it 1573 if (!$this->AllowEmpty && empty($this->Body)) { 1574 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); 1575 } 1576 1577 //Trim subject consistently 1578 $this->Subject = trim($this->Subject); 1579 //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) 1580 $this->MIMEHeader = ''; 1581 $this->MIMEBody = $this->createBody(); 1582 //createBody may have added some headers, so retain them 1583 $tempheaders = $this->MIMEHeader; 1584 $this->MIMEHeader = $this->createHeader(); 1585 $this->MIMEHeader .= $tempheaders; 1586 1587 //To capture the complete message when using mail(), create 1588 //an extra header list which createHeader() doesn't fold in 1589 if ('mail' === $this->Mailer) { 1590 if (count($this->to) > 0) { 1591 $this->mailHeader .= $this->addrAppend('To', $this->to); 1592 } else { 1593 $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); 1594 } 1595 $this->mailHeader .= $this->headerLine( 1596 'Subject', 1597 $this->encodeHeader($this->secureHeader($this->Subject)) 1598 ); 1599 } 1600 1601 //Sign with DKIM if enabled 1602 if ( 1603 !empty($this->DKIM_domain) 1604 && !empty($this->DKIM_selector) 1605 && (!empty($this->DKIM_private_string) 1606 || (!empty($this->DKIM_private) 1607 && static::isPermittedPath($this->DKIM_private) 1608 && file_exists($this->DKIM_private) 1609 ) 1610 ) 1611 ) { 1612 $header_dkim = $this->DKIM_Add( 1613 $this->MIMEHeader . $this->mailHeader, 1614 $this->encodeHeader($this->secureHeader($this->Subject)), 1615 $this->MIMEBody 1616 ); 1617 $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . 1618 static::normalizeBreaks($header_dkim) . static::$LE; 1619 } 1620 1621 return true; 1622 } catch (Exception $exc) { 1623 $this->setError($exc->getMessage()); 1624 if ($this->exceptions) { 1625 throw $exc; 1626 } 1627 1628 return false; 1629 } 1630 } 1631 1632 /** 1633 * Actually send a message via the selected mechanism. 1634 * 1635 * @throws Exception 1636 * 1637 * @return bool 1638 */ 1639 public function postSend() 1640 { 1641 try { 1642 //Choose the mailer and send through it 1643 switch ($this->Mailer) { 1644 case 'sendmail': 1645 case 'qmail': 1646 return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); 1647 case 'smtp': 1648 return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); 1649 case 'mail': 1650 return $this->mailSend($this->MIMEHeader, $this->MIMEBody); 1651 default: 1652 $sendMethod = $this->Mailer . 'Send'; 1653 if (method_exists($this, $sendMethod)) { 1654 return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); 1655 } 1656 1657 return $this->mailSend($this->MIMEHeader, $this->MIMEBody); 1658 } 1659 } catch (Exception $exc) { 1660 if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true) { 1661 $this->smtp->reset(); 1662 } 1663 $this->setError($exc->getMessage()); 1664 $this->edebug($exc->getMessage()); 1665 if ($this->exceptions) { 1666 throw $exc; 1667 } 1668 } 1669 1670 return false; 1671 } 1672 1673 /** 1674 * Send mail using the $Sendmail program. 1675 * 1676 * @see PHPMailer::$Sendmail 1677 * 1678 * @param string $header The message headers 1679 * @param string $body The message body 1680 * 1681 * @throws Exception 1682 * 1683 * @return bool 1684 */ 1685 protected function sendmailSend($header, $body) 1686 { 1687 if ($this->Mailer === 'qmail') { 1688 $this->edebug('Sending with qmail'); 1689 } else { 1690 $this->edebug('Sending with sendmail'); 1691 } 1692 $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; 1693 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver 1694 //A space after `-f` is optional, but there is a long history of its presence 1695 //causing problems, so we don't use one 1696 //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html 1697 //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html 1698 //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html 1699 //Example problem: https://www.drupal.org/node/1057954 1700 if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) { 1701 //PHP config has a sender address we can use 1702 $this->Sender = ini_get('sendmail_from'); 1703 } 1704 //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. 1705 if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { 1706 if ($this->Mailer === 'qmail') { 1707 $sendmailFmt = '%s -f%s'; 1708 } else { 1709 $sendmailFmt = '%s -oi -f%s -t'; 1710 } 1711 } else { 1712 //allow sendmail to choose a default envelope sender. It may 1713 //seem preferable to force it to use the From header as with 1714 //SMTP, but that introduces new problems (see 1715 //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and 1716 //it has historically worked this way. 1717 $sendmailFmt = '%s -oi -t'; 1718 } 1719 1720 $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); 1721 $this->edebug('Sendmail path: ' . $this->Sendmail); 1722 $this->edebug('Sendmail command: ' . $sendmail); 1723 $this->edebug('Envelope sender: ' . $this->Sender); 1724 $this->edebug("Headers: {$header}"); 1725 1726 if ($this->SingleTo) { 1727 foreach ($this->SingleToArray as $toAddr) { 1728 $mail = @popen($sendmail, 'w'); 1729 if (!$mail) { 1730 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 1731 } 1732 $this->edebug("To: {$toAddr}"); 1733 fwrite($mail, 'To: ' . $toAddr . "\n"); 1734 fwrite($mail, $header); 1735 fwrite($mail, $body); 1736 $result = pclose($mail); 1737 $addrinfo = static::parseAddresses($toAddr, true, $this->charSet); 1738 $this->doCallback( 1739 ($result === 0), 1740 [[$addrinfo['address'], $addrinfo['name']]], 1741 $this->cc, 1742 $this->bcc, 1743 $this->Subject, 1744 $body, 1745 $this->From, 1746 [] 1747 ); 1748 $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); 1749 if (0 !== $result) { 1750 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 1751 } 1752 } 1753 } else { 1754 $mail = @popen($sendmail, 'w'); 1755 if (!$mail) { 1756 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 1757 } 1758 fwrite($mail, $header); 1759 fwrite($mail, $body); 1760 $result = pclose($mail); 1761 $this->doCallback( 1762 ($result === 0), 1763 $this->to, 1764 $this->cc, 1765 $this->bcc, 1766 $this->Subject, 1767 $body, 1768 $this->From, 1769 [] 1770 ); 1771 $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); 1772 if (0 !== $result) { 1773 throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); 1774 } 1775 } 1776 1777 return true; 1778 } 1779 1780 /** 1781 * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. 1782 * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. 1783 * 1784 * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report 1785 * 1786 * @param string $string The string to be validated 1787 * 1788 * @return bool 1789 */ 1790 protected static function isShellSafe($string) 1791 { 1792 //Future-proof 1793 if ( 1794 escapeshellcmd($string) !== $string 1795 || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) 1796 ) { 1797 return false; 1798 } 1799 1800 $length = strlen($string); 1801 1802 for ($i = 0; $i < $length; ++$i) { 1803 $c = $string[$i]; 1804 1805 //All other characters have a special meaning in at least one common shell, including = and +. 1806 //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. 1807 //Note that this does permit non-Latin alphanumeric characters based on the current locale. 1808 if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { 1809 return false; 1810 } 1811 } 1812 1813 return true; 1814 } 1815 1816 /** 1817 * Check whether a file path is of a permitted type. 1818 * Used to reject URLs and phar files from functions that access local file paths, 1819 * such as addAttachment. 1820 * 1821 * @param string $path A relative or absolute path to a file 1822 * 1823 * @return bool 1824 */ 1825 protected static function isPermittedPath($path) 1826 { 1827 //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1 1828 return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path); 1829 } 1830 1831 /** 1832 * Check whether a file path is safe, accessible, and readable. 1833 * 1834 * @param string $path A relative or absolute path to a file 1835 * 1836 * @return bool 1837 */ 1838 protected static function fileIsAccessible($path) 1839 { 1840 if (!static::isPermittedPath($path)) { 1841 return false; 1842 } 1843 $readable = file_exists($path); 1844 //If not a UNC path (expected to start with \\), check read permission, see #2069 1845 if (strpos($path, '\\\\') !== 0) { 1846 $readable = $readable && is_readable($path); 1847 } 1848 return $readable; 1849 } 1850 1851 /** 1852 * Send mail using the PHP mail() function. 1853 * 1854 * @see http://www.php.net/manual/en/book.mail.php 1855 * 1856 * @param string $header The message headers 1857 * @param string $body The message body 1858 * 1859 * @throws Exception 1860 * 1861 * @return bool 1862 */ 1863 protected function mailSend($header, $body) 1864 { 1865 $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; 1866 1867 $toArr = []; 1868 foreach ($this->to as $toaddr) { 1869 $toArr[] = $this->addrFormat($toaddr); 1870 } 1871 $to = implode(', ', $toArr); 1872 1873 $params = null; 1874 //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver 1875 //A space after `-f` is optional, but there is a long history of its presence 1876 //causing problems, so we don't use one 1877 //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html 1878 //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html 1879 //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html 1880 //Example problem: https://www.drupal.org/node/1057954 1881 //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. 1882 if (empty($this->Sender) && !empty(ini_get('sendmail_from'))) { 1883 //PHP config has a sender address we can use 1884 $this->Sender = ini_get('sendmail_from'); 1885 } 1886 if (!empty($this->Sender) && static::validateAddress($this->Sender)) { 1887 if (self::isShellSafe($this->Sender)) { 1888 $params = sprintf('-f%s', $this->Sender); 1889 } 1890 $old_from = ini_get('sendmail_from'); 1891 ini_set('sendmail_from', $this->Sender); 1892 } 1893 $result = false; 1894 if ($this->SingleTo && count($toArr) > 1) { 1895 foreach ($toArr as $toAddr) { 1896 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); 1897 $addrinfo = static::parseAddresses($toAddr, true, $this->charSet); 1898 $this->doCallback( 1899 $result, 1900 [[$addrinfo['address'], $addrinfo['name']]], 1901 $this->cc, 1902 $this->bcc, 1903 $this->Subject, 1904 $body, 1905 $this->From, 1906 [] 1907 ); 1908 } 1909 } else { 1910 $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); 1911 $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); 1912 } 1913 if (isset($old_from)) { 1914 ini_set('sendmail_from', $old_from); 1915 } 1916 if (!$result) { 1917 throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); 1918 } 1919 1920 return true; 1921 } 1922 1923 /** 1924 * Get an instance to use for SMTP operations. 1925 * Override this function to load your own SMTP implementation, 1926 * or set one with setSMTPInstance. 1927 * 1928 * @return SMTP 1929 */ 1930 public function getSMTPInstance() 1931 { 1932 if (!is_object($this->smtp)) { 1933 $this->smtp = new SMTP(); 1934 } 1935 1936 return $this->smtp; 1937 } 1938 1939 /** 1940 * Provide an instance to use for SMTP operations. 1941 * 1942 * @return SMTP 1943 */ 1944 public function setSMTPInstance(SMTP $smtp) 1945 { 1946 $this->smtp = $smtp; 1947 1948 return $this->smtp; 1949 } 1950 1951 /** 1952 * Send mail via SMTP. 1953 * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. 1954 * 1955 * @see PHPMailer::setSMTPInstance() to use a different class. 1956 * 1957 * @uses \PHPMailer\PHPMailer\SMTP 1958 * 1959 * @param string $header The message headers 1960 * @param string $body The message body 1961 * 1962 * @throws Exception 1963 * 1964 * @return bool 1965 */ 1966 protected function smtpSend($header, $body) 1967 { 1968 $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; 1969 $bad_rcpt = []; 1970 if (!$this->smtpConnect($this->SMTPOptions)) { 1971 throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); 1972 } 1973 //Sender already validated in preSend() 1974 if ('' === $this->Sender) { 1975 $smtp_from = $this->From; 1976 } else { 1977 $smtp_from = $this->Sender; 1978 } 1979 if (!$this->smtp->mail($smtp_from)) { 1980 $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); 1981 throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); 1982 } 1983 1984 $callbacks = []; 1985 //Attempt to send to all recipients 1986 foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { 1987 foreach ($togroup as $to) { 1988 if (!$this->smtp->recipient($to[0], $this->dsn)) { 1989 $error = $this->smtp->getError(); 1990 $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; 1991 $isSent = false; 1992 } else { 1993 $isSent = true; 1994 } 1995 1996 $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]]; 1997 } 1998 } 1999 2000 //Only send the DATA command if we have viable recipients 2001 if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { 2002 throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); 2003 } 2004 2005 $smtp_transaction_id = $this->smtp->getLastTransactionID(); 2006 2007 if ($this->SMTPKeepAlive) { 2008 $this->smtp->reset(); 2009 } else { 2010 $this->smtp->quit(); 2011 $this->smtp->close(); 2012 } 2013 2014 foreach ($callbacks as $cb) { 2015 $this->doCallback( 2016 $cb['issent'], 2017 [[$cb['to'], $cb['name']]], 2018 [], 2019 [], 2020 $this->Subject, 2021 $body, 2022 $this->From, 2023 ['smtp_transaction_id' => $smtp_transaction_id] 2024 ); 2025 } 2026 2027 //Create error message for any bad addresses 2028 if (count($bad_rcpt) > 0) { 2029 $errstr = ''; 2030 foreach ($bad_rcpt as $bad) { 2031 $errstr .= $bad['to'] . ': ' . $bad['error']; 2032 } 2033 throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); 2034 } 2035 2036 return true; 2037 } 2038 2039 /** 2040 * Initiate a connection to an SMTP server. 2041 * Returns false if the operation failed. 2042 * 2043 * @param array $options An array of options compatible with stream_context_create() 2044 * 2045 * @throws Exception 2046 * 2047 * @uses \PHPMailer\PHPMailer\SMTP 2048 * 2049 * @return bool 2050 */ 2051 public function smtpConnect($options = null) 2052 { 2053 if (null === $this->smtp) { 2054 $this->smtp = $this->getSMTPInstance(); 2055 } 2056 2057 //If no options are provided, use whatever is set in the instance 2058 if (null === $options) { 2059 $options = $this->SMTPOptions; 2060 } 2061 2062 //Already connected? 2063 if ($this->smtp->connected()) { 2064 return true; 2065 } 2066 2067 $this->smtp->setTimeout($this->Timeout); 2068 $this->smtp->setDebugLevel($this->SMTPDebug); 2069 $this->smtp->setDebugOutput($this->Debugoutput); 2070 $this->smtp->setVerp($this->do_verp); 2071 $hosts = explode(';', $this->Host); 2072 $lastexception = null; 2073 2074 foreach ($hosts as $hostentry) { 2075 $hostinfo = []; 2076 if ( 2077 !preg_match( 2078 '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', 2079 trim($hostentry), 2080 $hostinfo 2081 ) 2082 ) { 2083 $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); 2084 //Not a valid host entry 2085 continue; 2086 } 2087 //$hostinfo[1]: optional ssl or tls prefix 2088 //$hostinfo[2]: the hostname 2089 //$hostinfo[3]: optional port number 2090 //The host string prefix can temporarily override the current setting for SMTPSecure 2091 //If it's not specified, the default value is used 2092 2093 //Check the host name is a valid name or IP address before trying to use it 2094 if (!static::isValidHost($hostinfo[2])) { 2095 $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); 2096 continue; 2097 } 2098 $prefix = ''; 2099 $secure = $this->SMTPSecure; 2100 $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure); 2101 if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) { 2102 $prefix = 'ssl://'; 2103 $tls = false; //Can't have SSL and TLS at the same time 2104 $secure = static::ENCRYPTION_SMTPS; 2105 } elseif ('tls' === $hostinfo[1]) { 2106 $tls = true; 2107 //TLS doesn't use a prefix 2108 $secure = static::ENCRYPTION_STARTTLS; 2109 } 2110 //Do we need the OpenSSL extension? 2111 $sslext = defined('OPENSSL_ALGO_SHA256'); 2112 if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { 2113 //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled 2114 if (!$sslext) { 2115 throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); 2116 } 2117 } 2118 $host = $hostinfo[2]; 2119 $port = $this->Port; 2120 if ( 2121 array_key_exists(3, $hostinfo) && 2122 is_numeric($hostinfo[3]) && 2123 $hostinfo[3] > 0 && 2124 $hostinfo[3] < 65536 2125 ) { 2126 $port = (int) $hostinfo[3]; 2127 } 2128 if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { 2129 try { 2130 if ($this->Helo) { 2131 $hello = $this->Helo; 2132 } else { 2133 $hello = $this->serverHostname(); 2134 } 2135 $this->smtp->hello($hello); 2136 //Automatically enable TLS encryption if: 2137 //* it's not disabled 2138 //* we have openssl extension 2139 //* we are not already using SSL 2140 //* the server offers STARTTLS 2141 if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) { 2142 $tls = true; 2143 } 2144 if ($tls) { 2145 if (!$this->smtp->startTLS()) { 2146 throw new Exception($this->lang('connect_host')); 2147 } 2148 //We must resend EHLO after TLS negotiation 2149 $this->smtp->hello($hello); 2150 } 2151 if ( 2152 $this->SMTPAuth && !$this->smtp->authenticate( 2153 $this->Username, 2154 $this->Password, 2155 $this->AuthType, 2156 $this->oauth 2157 ) 2158 ) { 2159 throw new Exception($this->lang('authenticate')); 2160 } 2161 2162 return true; 2163 } catch (Exception $exc) { 2164 $lastexception = $exc; 2165 $this->edebug($exc->getMessage()); 2166 //We must have connected, but then failed TLS or Auth, so close connection nicely 2167 $this->smtp->quit(); 2168 } 2169 } 2170 } 2171 //If we get here, all connection attempts have failed, so close connection hard 2172 $this->smtp->close(); 2173 //As we've caught all exceptions, just report whatever the last one was 2174 if ($this->exceptions && null !== $lastexception) { 2175 throw $lastexception; 2176 } 2177 2178 return false; 2179 } 2180 2181 /** 2182 * Close the active SMTP session if one exists. 2183 */ 2184 public function smtpClose() 2185 { 2186 if ((null !== $this->smtp) && $this->smtp->connected()) { 2187 $this->smtp->quit(); 2188 $this->smtp->close(); 2189 } 2190 } 2191 2192 /** 2193 * Set the language for error messages. 2194 * The default language is English. 2195 * 2196 * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") 2197 * Optionally, the language code can be enhanced with a 4-character 2198 * script annotation and/or a 2-character country annotation. 2199 * @param string $lang_path Path to the language file directory, with trailing separator (slash).D 2200 * Do not set this from user input! 2201 * 2202 * @return bool Returns true if the requested language was loaded, false otherwise. 2203 */ 2204 public function setLanguage($langcode = 'en', $lang_path = '') 2205 { 2206 //Backwards compatibility for renamed language codes 2207 $renamed_langcodes = [ 2208 'br' => 'pt_br', 2209 'cz' => 'cs', 2210 'dk' => 'da', 2211 'no' => 'nb', 2212 'se' => 'sv', 2213 'rs' => 'sr', 2214 'tg' => 'tl', 2215 'am' => 'hy', 2216 ]; 2217 2218 if (array_key_exists($langcode, $renamed_langcodes)) { 2219 $langcode = $renamed_langcodes[$langcode]; 2220 } 2221 2222 //Define full set of translatable strings in English 2223 $PHPMAILER_LANG = [ 2224 'authenticate' => 'SMTP Error: Could not authenticate.', 2225 'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' . 2226 ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . 2227 ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', 2228 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 2229 'data_not_accepted' => 'SMTP Error: data not accepted.', 2230 'empty_message' => 'Message body empty', 2231 'encoding' => 'Unknown encoding: ', 2232 'execute' => 'Could not execute: ', 2233 'extension_missing' => 'Extension missing: ', 2234 'file_access' => 'Could not access file: ', 2235 'file_open' => 'File Error: Could not open file: ', 2236 'from_failed' => 'The following From address failed: ', 2237 'instantiate' => 'Could not instantiate mail function.', 2238 'invalid_address' => 'Invalid address: ', 2239 'invalid_header' => 'Invalid header name or value', 2240 'invalid_hostentry' => 'Invalid hostentry: ', 2241 'invalid_host' => 'Invalid host: ', 2242 'mailer_not_supported' => ' mailer is not supported.', 2243 'provide_address' => 'You must provide at least one recipient email address.', 2244 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 2245 'signing' => 'Signing Error: ', 2246 'smtp_code' => 'SMTP code: ', 2247 'smtp_code_ex' => 'Additional SMTP info: ', 2248 'smtp_connect_failed' => 'SMTP connect() failed.', 2249 'smtp_detail' => 'Detail: ', 2250 'smtp_error' => 'SMTP server error: ', 2251 'variable_set' => 'Cannot set or reset variable: ', 2252 ]; 2253 if (empty($lang_path)) { 2254 //Calculate an absolute path so it can work if CWD is not here 2255 $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; 2256 } 2257 2258 //Validate $langcode 2259 $foundlang = true; 2260 $langcode = strtolower($langcode); 2261 if ( 2262 !preg_match('/^(?P<lang>[a-z]{2})(?P<script>_[a-z]{4})?(?P<country>_[a-z]{2})?$/', $langcode, $matches) 2263 && $langcode !== 'en' 2264 ) { 2265 $foundlang = false; 2266 $langcode = 'en'; 2267 } 2268 2269 //There is no English translation file 2270 if ('en' !== $langcode) { 2271 $langcodes = []; 2272 if (!empty($matches['script']) && !empty($matches['country'])) { 2273 $langcodes[] = $matches['lang'] . $matches['script'] . $matches['country']; 2274 } 2275 if (!empty($matches['country'])) { 2276 $langcodes[] = $matches['lang'] . $matches['country']; 2277 } 2278 if (!empty($matches['script'])) { 2279 $langcodes[] = $matches['lang'] . $matches['script']; 2280 } 2281 $langcodes[] = $matches['lang']; 2282 2283 //Try and find a readable language file for the requested language. 2284 $foundFile = false; 2285 foreach ($langcodes as $code) { 2286 $lang_file = $lang_path . 'phpmailer.lang-' . $code . '.php'; 2287 if (static::fileIsAccessible($lang_file)) { 2288 $foundFile = true; 2289 break; 2290 } 2291 } 2292 2293 if ($foundFile === false) { 2294 $foundlang = false; 2295 } else { 2296 $lines = file($lang_file); 2297 foreach ($lines as $line) { 2298 //Translation file lines look like this: 2299 //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.'; 2300 //These files are parsed as text and not PHP so as to avoid the possibility of code injection 2301 //See https://blog.stevenlevithan.com/archives/match-quoted-string 2302 $matches = []; 2303 if ( 2304 preg_match( 2305 '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/', 2306 $line, 2307 $matches 2308 ) && 2309 //Ignore unknown translation keys 2310 array_key_exists($matches[1], $PHPMAILER_LANG) 2311 ) { 2312 //Overwrite language-specific strings so we'll never have missing translation keys. 2313 $PHPMAILER_LANG[$matches[1]] = (string)$matches[3]; 2314 } 2315 } 2316 } 2317 } 2318 $this->language = $PHPMAILER_LANG; 2319 2320 return $foundlang; //Returns false if language not found 2321 } 2322 2323 /** 2324 * Get the array of strings for the current language. 2325 * 2326 * @return array 2327 */ 2328 public function getTranslations() 2329 { 2330 if (empty($this->language)) { 2331 $this->setLanguage(); // Set the default language. 2332 } 2333 2334 return $this->language; 2335 } 2336 2337 /** 2338 * Create recipient headers. 2339 * 2340 * @param string $type 2341 * @param array $addr An array of recipients, 2342 * where each recipient is a 2-element indexed array with element 0 containing an address 2343 * and element 1 containing a name, like: 2344 * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']] 2345 * 2346 * @return string 2347 */ 2348 public function addrAppend($type, $addr) 2349 { 2350 $addresses = []; 2351 foreach ($addr as $address) { 2352 $addresses[] = $this->addrFormat($address); 2353 } 2354 2355 return $type . ': ' . implode(', ', $addresses) . static::$LE; 2356 } 2357 2358 /** 2359 * Format an address for use in a message header. 2360 * 2361 * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like 2362 * ['joe@example.com', 'Joe User'] 2363 * 2364 * @return string 2365 */ 2366 public function addrFormat($addr) 2367 { 2368 if (empty($addr[1])) { //No name provided 2369 return $this->secureHeader($addr[0]); 2370 } 2371 2372 return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . 2373 ' <' . $this->secureHeader($addr[0]) . '>'; 2374 } 2375 2376 /** 2377 * Word-wrap message. 2378 * For use with mailers that do not automatically perform wrapping 2379 * and for quoted-printable encoded messages. 2380 * Original written by philippe. 2381 * 2382 * @param string $message The message to wrap 2383 * @param int $length The line length to wrap to 2384 * @param bool $qp_mode Whether to run in Quoted-Printable mode 2385 * 2386 * @return string 2387 */ 2388 public function wrapText($message, $length, $qp_mode = false) 2389 { 2390 if ($qp_mode) { 2391 $soft_break = sprintf(' =%s', static::$LE); 2392 } else { 2393 $soft_break = static::$LE; 2394 } 2395 //If utf-8 encoding is used, we will need to make sure we don't 2396 //split multibyte characters when we wrap 2397 $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet); 2398 $lelen = strlen(static::$LE); 2399 $crlflen = strlen(static::$LE); 2400 2401 $message = static::normalizeBreaks($message); 2402 //Remove a trailing line break 2403 if (substr($message, -$lelen) === static::$LE) { 2404 $message = substr($message, 0, -$lelen); 2405 } 2406 2407 //Split message into lines 2408 $lines = explode(static::$LE, $message); 2409 //Message will be rebuilt in here 2410 $message = ''; 2411 foreach ($lines as $line) { 2412 $words = explode(' ', $line); 2413 $buf = ''; 2414 $firstword = true; 2415 foreach ($words as $word) { 2416 if ($qp_mode && (strlen($word) > $length)) { 2417 $space_left = $length - strlen($buf) - $crlflen; 2418 if (!$firstword) { 2419 if ($space_left > 20) { 2420 $len = $space_left; 2421 if ($is_utf8) { 2422 $len = $this->utf8CharBoundary($word, $len); 2423 } elseif ('=' === substr($word, $len - 1, 1)) { 2424 --$len; 2425 } elseif ('=' === substr($word, $len - 2, 1)) { 2426 $len -= 2; 2427 } 2428 $part = substr($word, 0, $len); 2429 $word = substr($word, $len); 2430 $buf .= ' ' . $part; 2431 $message .= $buf . sprintf('=%s', static::$LE); 2432 } else { 2433 $message .= $buf . $soft_break; 2434 } 2435 $buf = ''; 2436 } 2437 while ($word !== '') { 2438 if ($length <= 0) { 2439 break; 2440 } 2441 $len = $length; 2442 if ($is_utf8) { 2443 $len = $this->utf8CharBoundary($word, $len); 2444 } elseif ('=' === substr($word, $len - 1, 1)) { 2445 --$len; 2446 } elseif ('=' === substr($word, $len - 2, 1)) { 2447 $len -= 2; 2448 } 2449 $part = substr($word, 0, $len); 2450 $word = (string) substr($word, $len); 2451 2452 if ($word !== '') { 2453 $message .= $part . sprintf('=%s', static::$LE); 2454 } else { 2455 $buf = $part; 2456 } 2457 } 2458 } else { 2459 $buf_o = $buf; 2460 if (!$firstword) { 2461 $buf .= ' '; 2462 } 2463 $buf .= $word; 2464 2465 if ('' !== $buf_o && strlen($buf) > $length) { 2466 $message .= $buf_o . $soft_break; 2467 $buf = $word; 2468 } 2469 } 2470 $firstword = false; 2471 } 2472 $message .= $buf . static::$LE; 2473 } 2474 2475 return $message; 2476 } 2477 2478 /** 2479 * Find the last character boundary prior to $maxLength in a utf-8 2480 * quoted-printable encoded string. 2481 * Original written by Colin Brown. 2482 * 2483 * @param string $encodedText utf-8 QP text 2484 * @param int $maxLength Find the last character boundary prior to this length 2485 * 2486 * @return int 2487 */ 2488 public function utf8CharBoundary($encodedText, $maxLength) 2489 { 2490 $foundSplitPos = false; 2491 $lookBack = 3; 2492 while (!$foundSplitPos) { 2493 $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); 2494 $encodedCharPos = strpos($lastChunk, '='); 2495 if (false !== $encodedCharPos) { 2496 //Found start of encoded character byte within $lookBack block. 2497 //Check the encoded byte value (the 2 chars after the '=') 2498 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); 2499 $dec = hexdec($hex); 2500 if ($dec < 128) { 2501 //Single byte character. 2502 //If the encoded char was found at pos 0, it will fit 2503 //otherwise reduce maxLength to start of the encoded char 2504 if ($encodedCharPos > 0) { 2505 $maxLength -= $lookBack - $encodedCharPos; 2506 } 2507 $foundSplitPos = true; 2508 } elseif ($dec >= 192) { 2509 //First byte of a multi byte character 2510 //Reduce maxLength to split at start of character 2511 $maxLength -= $lookBack - $encodedCharPos; 2512 $foundSplitPos = true; 2513 } elseif ($dec < 192) { 2514 //Middle byte of a multi byte character, look further back 2515 $lookBack += 3; 2516 } 2517 } else { 2518 //No encoded character found 2519 $foundSplitPos = true; 2520 } 2521 } 2522 2523 return $maxLength; 2524 } 2525 2526 /** 2527 * Apply word wrapping to the message body. 2528 * Wraps the message body to the number of chars set in the WordWrap property. 2529 * You should only do this to plain-text bodies as wrapping HTML tags may break them. 2530 * This is called automatically by createBody(), so you don't need to call it yourself. 2531 */ 2532 public function setWordWrap() 2533 { 2534 if ($this->WordWrap < 1) { 2535 return; 2536 } 2537 2538 switch ($this->message_type) { 2539 case 'alt': 2540 case 'alt_inline': 2541 case 'alt_attach': 2542 case 'alt_inline_attach': 2543 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); 2544 break; 2545 default: 2546 $this->Body = $this->wrapText($this->Body, $this->WordWrap); 2547 break; 2548 } 2549 } 2550 2551 /** 2552 * Assemble message headers. 2553 * 2554 * @return string The assembled headers 2555 */ 2556 public function createHeader() 2557 { 2558 $result = ''; 2559 2560 $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate); 2561 2562 //The To header is created automatically by mail(), so needs to be omitted here 2563 if ('mail' !== $this->Mailer) { 2564 if ($this->SingleTo) { 2565 foreach ($this->to as $toaddr) { 2566 $this->SingleToArray[] = $this->addrFormat($toaddr); 2567 } 2568 } elseif (count($this->to) > 0) { 2569 $result .= $this->addrAppend('To', $this->to); 2570 } elseif (count($this->cc) === 0) { 2571 $result .= $this->headerLine('To', 'undisclosed-recipients:;'); 2572 } 2573 } 2574 $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]); 2575 2576 //sendmail and mail() extract Cc from the header before sending 2577 if (count($this->cc) > 0) { 2578 $result .= $this->addrAppend('Cc', $this->cc); 2579 } 2580 2581 //sendmail and mail() extract Bcc from the header before sending 2582 if ( 2583 ( 2584 'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer 2585 ) 2586 && count($this->bcc) > 0 2587 ) { 2588 $result .= $this->addrAppend('Bcc', $this->bcc); 2589 } 2590 2591 if (count($this->ReplyTo) > 0) { 2592 $result .= $this->addrAppend('Reply-To', $this->ReplyTo); 2593 } 2594 2595 //mail() sets the subject itself 2596 if ('mail' !== $this->Mailer) { 2597 $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); 2598 } 2599 2600 //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 2601 //https://tools.ietf.org/html/rfc5322#section-3.6.4 2602 if ( 2603 '' !== $this->MessageID && 2604 preg_match( 2605 '/^<((([a-z\d!#$%&\'*+\/=?^_`{|}~-]+(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)' . 2606 '|("(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]|[\x21\x23-\x5B\x5D-\x7E])' . 2607 '|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*"))@(([a-z\d!#$%&\'*+\/=?^_`{|}~-]+' . 2608 '(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)|(\[(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]' . 2609 '|[\x21-\x5A\x5E-\x7E])|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*\])))>$/Di', 2610 $this->MessageID 2611 ) 2612 ) { 2613 $this->lastMessageID = $this->MessageID; 2614 } else { 2615 $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); 2616 } 2617 $result .= $this->headerLine('Message-ID', $this->lastMessageID); 2618 if (null !== $this->Priority) { 2619 $result .= $this->headerLine('X-Priority', $this->Priority); 2620 } 2621 if ('' === $this->XMailer) { 2622 $result .= $this->headerLine( 2623 'X-Mailer', 2624 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)' 2625 ); 2626 } else { 2627 $myXmailer = trim($this->XMailer); 2628 if ($myXmailer) { 2629 $result .= $this->headerLine('X-Mailer', $myXmailer); 2630 } 2631 } 2632 2633 if ('' !== $this->ConfirmReadingTo) { 2634 $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); 2635 } 2636 2637 //Add custom headers 2638 foreach ($this->CustomHeader as $header) { 2639 $result .= $this->headerLine( 2640 trim($header[0]), 2641 $this->encodeHeader(trim($header[1])) 2642 ); 2643 } 2644 if (!$this->sign_key_file) { 2645 $result .= $this->headerLine('MIME-Version', '1.0'); 2646 $result .= $this->getMailMIME(); 2647 } 2648 2649 return $result; 2650 } 2651 2652 /** 2653 * Get the message MIME type headers. 2654 * 2655 * @return string 2656 */ 2657 public function getMailMIME() 2658 { 2659 $result = ''; 2660 $ismultipart = true; 2661 switch ($this->message_type) { 2662 case 'inline': 2663 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); 2664 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); 2665 break; 2666 case 'attach': 2667 case 'inline_attach': 2668 case 'alt_attach': 2669 case 'alt_inline_attach': 2670 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';'); 2671 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); 2672 break; 2673 case 'alt': 2674 case 'alt_inline': 2675 $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); 2676 $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); 2677 break; 2678 default: 2679 //Catches case 'plain': and case '': 2680 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); 2681 $ismultipart = false; 2682 break; 2683 } 2684 //RFC1341 part 5 says 7bit is assumed if not specified 2685 if (static::ENCODING_7BIT !== $this->Encoding) { 2686 //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE 2687 if ($ismultipart) { 2688 if (static::ENCODING_8BIT === $this->Encoding) { 2689 $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT); 2690 } 2691 //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible 2692 } else { 2693 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); 2694 } 2695 } 2696 2697 return $result; 2698 } 2699 2700 /** 2701 * Returns the whole MIME message. 2702 * Includes complete headers and body. 2703 * Only valid post preSend(). 2704 * 2705 * @see PHPMailer::preSend() 2706 * 2707 * @return string 2708 */ 2709 public function getSentMIMEMessage() 2710 { 2711 return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) . 2712 static::$LE . static::$LE . $this->MIMEBody; 2713 } 2714 2715 /** 2716 * Create a unique ID to use for boundaries. 2717 * 2718 * @return string 2719 */ 2720 protected function generateId() 2721 { 2722 $len = 32; //32 bytes = 256 bits 2723 $bytes = ''; 2724 if (function_exists('random_bytes')) { 2725 try { 2726 $bytes = random_bytes($len); 2727 } catch (\Exception $e) { 2728 //Do nothing 2729 } 2730 } elseif (function_exists('openssl_random_pseudo_bytes')) { 2731 /** @noinspection CryptographicallySecureRandomnessInspection */ 2732 $bytes = openssl_random_pseudo_bytes($len); 2733 } 2734 if ($bytes === '') { 2735 //We failed to produce a proper random string, so make do. 2736 //Use a hash to force the length to the same as the other methods 2737 $bytes = hash('sha256', uniqid((string) mt_rand(), true), true); 2738 } 2739 2740 //We don't care about messing up base64 format here, just want a random string 2741 return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true))); 2742 } 2743 2744 /** 2745 * Assemble the message body. 2746 * Returns an empty string on failure. 2747 * 2748 * @throws Exception 2749 * 2750 * @return string The assembled message body 2751 */ 2752 public function createBody() 2753 { 2754 $body = ''; 2755 //Create unique IDs and preset boundaries 2756 $this->uniqueid = $this->generateId(); 2757 $this->boundary[1] = 'b1_' . $this->uniqueid; 2758 $this->boundary[2] = 'b2_' . $this->uniqueid; 2759 $this->boundary[3] = 'b3_' . $this->uniqueid; 2760 2761 if ($this->sign_key_file) { 2762 $body .= $this->getMailMIME() . static::$LE; 2763 } 2764 2765 $this->setWordWrap(); 2766 2767 $bodyEncoding = $this->Encoding; 2768 $bodyCharSet = $this->CharSet; 2769 //Can we do a 7-bit downgrade? 2770 if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) { 2771 $bodyEncoding = static::ENCODING_7BIT; 2772 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit 2773 $bodyCharSet = static::CHARSET_ASCII; 2774 } 2775 //If lines are too long, and we're not already using an encoding that will shorten them, 2776 //change to quoted-printable transfer encoding for the body part only 2777 if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) { 2778 $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE; 2779 } 2780 2781 $altBodyEncoding = $this->Encoding; 2782 $altBodyCharSet = $this->CharSet; 2783 //Can we do a 7-bit downgrade? 2784 if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) { 2785 $altBodyEncoding = static::ENCODING_7BIT; 2786 //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit 2787 $altBodyCharSet = static::CHARSET_ASCII; 2788 } 2789 //If lines are too long, and we're not already using an encoding that will shorten them, 2790 //change to quoted-printable transfer encoding for the alt body part only 2791 if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) { 2792 $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE; 2793 } 2794 //Use this as a preamble in all multipart message types 2795 $mimepre = 'This is a multi-part message in MIME format.' . static::$LE . static::$LE; 2796 switch ($this->message_type) { 2797 case 'inline': 2798 $body .= $mimepre; 2799 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); 2800 $body .= $this->encodeString($this->Body, $bodyEncoding); 2801 $body .= static::$LE; 2802 $body .= $this->attachAll('inline', $this->boundary[1]); 2803 break; 2804 case 'attach': 2805 $body .= $mimepre; 2806 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); 2807 $body .= $this->encodeString($this->Body, $bodyEncoding); 2808 $body .= static::$LE; 2809 $body .= $this->attachAll('attachment', $this->boundary[1]); 2810 break; 2811 case 'inline_attach': 2812 $body .= $mimepre; 2813 $body .= $this->textLine('--' . $this->boundary[1]); 2814 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); 2815 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); 2816 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); 2817 $body .= static::$LE; 2818 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); 2819 $body .= $this->encodeString($this->Body, $bodyEncoding); 2820 $body .= static::$LE; 2821 $body .= $this->attachAll('inline', $this->boundary[2]); 2822 $body .= static::$LE; 2823 $body .= $this->attachAll('attachment', $this->boundary[1]); 2824 break; 2825 case 'alt': 2826 $body .= $mimepre; 2827 $body .= $this->getBoundary( 2828 $this->boundary[1], 2829 $altBodyCharSet, 2830 static::CONTENT_TYPE_PLAINTEXT, 2831 $altBodyEncoding 2832 ); 2833 $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 2834 $body .= static::$LE; 2835 $body .= $this->getBoundary( 2836 $this->boundary[1], 2837 $bodyCharSet, 2838 static::CONTENT_TYPE_TEXT_HTML, 2839 $bodyEncoding 2840 ); 2841 $body .= $this->encodeString($this->Body, $bodyEncoding); 2842 $body .= static::$LE; 2843 if (!empty($this->Ical)) { 2844 $method = static::ICAL_METHOD_REQUEST; 2845 foreach (static::$IcalMethods as $imethod) { 2846 if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { 2847 $method = $imethod; 2848 break; 2849 } 2850 } 2851 $body .= $this->getBoundary( 2852 $this->boundary[1], 2853 '', 2854 static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, 2855 '' 2856 ); 2857 $body .= $this->encodeString($this->Ical, $this->Encoding); 2858 $body .= static::$LE; 2859 } 2860 $body .= $this->endBoundary($this->boundary[1]); 2861 break; 2862 case 'alt_inline': 2863 $body .= $mimepre; 2864 $body .= $this->getBoundary( 2865 $this->boundary[1], 2866 $altBodyCharSet, 2867 static::CONTENT_TYPE_PLAINTEXT, 2868 $altBodyEncoding 2869 ); 2870 $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 2871 $body .= static::$LE; 2872 $body .= $this->textLine('--' . $this->boundary[1]); 2873 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); 2874 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); 2875 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); 2876 $body .= static::$LE; 2877 $body .= $this->getBoundary( 2878 $this->boundary[2], 2879 $bodyCharSet, 2880 static::CONTENT_TYPE_TEXT_HTML, 2881 $bodyEncoding 2882 ); 2883 $body .= $this->encodeString($this->Body, $bodyEncoding); 2884 $body .= static::$LE; 2885 $body .= $this->attachAll('inline', $this->boundary[2]); 2886 $body .= static::$LE; 2887 $body .= $this->endBoundary($this->boundary[1]); 2888 break; 2889 case 'alt_attach': 2890 $body .= $mimepre; 2891 $body .= $this->textLine('--' . $this->boundary[1]); 2892 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); 2893 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); 2894 $body .= static::$LE; 2895 $body .= $this->getBoundary( 2896 $this->boundary[2], 2897 $altBodyCharSet, 2898 static::CONTENT_TYPE_PLAINTEXT, 2899 $altBodyEncoding 2900 ); 2901 $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 2902 $body .= static::$LE; 2903 $body .= $this->getBoundary( 2904 $this->boundary[2], 2905 $bodyCharSet, 2906 static::CONTENT_TYPE_TEXT_HTML, 2907 $bodyEncoding 2908 ); 2909 $body .= $this->encodeString($this->Body, $bodyEncoding); 2910 $body .= static::$LE; 2911 if (!empty($this->Ical)) { 2912 $method = static::ICAL_METHOD_REQUEST; 2913 foreach (static::$IcalMethods as $imethod) { 2914 if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { 2915 $method = $imethod; 2916 break; 2917 } 2918 } 2919 $body .= $this->getBoundary( 2920 $this->boundary[2], 2921 '', 2922 static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, 2923 '' 2924 ); 2925 $body .= $this->encodeString($this->Ical, $this->Encoding); 2926 } 2927 $body .= $this->endBoundary($this->boundary[2]); 2928 $body .= static::$LE; 2929 $body .= $this->attachAll('attachment', $this->boundary[1]); 2930 break; 2931 case 'alt_inline_attach': 2932 $body .= $mimepre; 2933 $body .= $this->textLine('--' . $this->boundary[1]); 2934 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); 2935 $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); 2936 $body .= static::$LE; 2937 $body .= $this->getBoundary( 2938 $this->boundary[2], 2939 $altBodyCharSet, 2940 static::CONTENT_TYPE_PLAINTEXT, 2941 $altBodyEncoding 2942 ); 2943 $body .= $this->encodeString($this->AltBody, $altBodyEncoding); 2944 $body .= static::$LE; 2945 $body .= $this->textLine('--' . $this->boundary[2]); 2946 $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); 2947 $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";'); 2948 $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); 2949 $body .= static::$LE; 2950 $body .= $this->getBoundary( 2951 $this->boundary[3], 2952 $bodyCharSet, 2953 static::CONTENT_TYPE_TEXT_HTML, 2954 $bodyEncoding 2955 ); 2956 $body .= $this->encodeString($this->Body, $bodyEncoding); 2957 $body .= static::$LE; 2958 $body .= $this->attachAll('inline', $this->boundary[3]); 2959 $body .= static::$LE; 2960 $body .= $this->endBoundary($this->boundary[2]); 2961 $body .= static::$LE; 2962 $body .= $this->attachAll('attachment', $this->boundary[1]); 2963 break; 2964 default: 2965 //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types 2966 //Reset the `Encoding` property in case we changed it for line length reasons 2967 $this->Encoding = $bodyEncoding; 2968 $body .= $this->encodeString($this->Body, $this->Encoding); 2969 break; 2970 } 2971 2972 if ($this->isError()) { 2973 $body = ''; 2974 if ($this->exceptions) { 2975 throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); 2976 } 2977 } elseif ($this->sign_key_file) { 2978 try { 2979 if (!defined('PKCS7_TEXT')) { 2980 throw new Exception($this->lang('extension_missing') . 'openssl'); 2981 } 2982 2983 $file = tempnam(sys_get_temp_dir(), 'srcsign'); 2984 $signed = tempnam(sys_get_temp_dir(), 'mailsign'); 2985 file_put_contents($file, $body); 2986 2987 //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 2988 if (empty($this->sign_extracerts_file)) { 2989 $sign = @openssl_pkcs7_sign( 2990 $file, 2991 $signed, 2992 'file://' . realpath($this->sign_cert_file), 2993 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], 2994 [] 2995 ); 2996 } else { 2997 $sign = @openssl_pkcs7_sign( 2998 $file, 2999 $signed, 3000 'file://' . realpath($this->sign_cert_file), 3001 ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], 3002 [], 3003 PKCS7_DETACHED, 3004 $this->sign_extracerts_file 3005 ); 3006 } 3007 3008 @unlink($file); 3009 if ($sign) { 3010 $body = file_get_contents($signed); 3011 @unlink($signed); 3012 //The message returned by openssl contains both headers and body, so need to split them up 3013 $parts = explode("\n\n", $body, 2); 3014 $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE; 3015 $body = $parts[1]; 3016 } else { 3017 @unlink($signed); 3018 throw new Exception($this->lang('signing') . openssl_error_string()); 3019 } 3020 } catch (Exception $exc) { 3021 $body = ''; 3022 if ($this->exceptions) { 3023 throw $exc; 3024 } 3025 } 3026 } 3027 3028 return $body; 3029 } 3030 3031 /** 3032 * Return the start of a message boundary. 3033 * 3034 * @param string $boundary 3035 * @param string $charSet 3036 * @param string $contentType 3037 * @param string $encoding 3038 * 3039 * @return string 3040 */ 3041 protected function getBoundary($boundary, $charSet, $contentType, $encoding) 3042 { 3043 $result = ''; 3044 if ('' === $charSet) { 3045 $charSet = $this->CharSet; 3046 } 3047 if ('' === $contentType) { 3048 $contentType = $this->ContentType; 3049 } 3050 if ('' === $encoding) { 3051 $encoding = $this->Encoding; 3052 } 3053 $result .= $this->textLine('--' . $boundary); 3054 $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); 3055 $result .= static::$LE; 3056 //RFC1341 part 5 says 7bit is assumed if not specified 3057 if (static::ENCODING_7BIT !== $encoding) { 3058 $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); 3059 } 3060 $result .= static::$LE; 3061 3062 return $result; 3063 } 3064 3065 /** 3066 * Return the end of a message boundary. 3067 * 3068 * @param string $boundary 3069 * 3070 * @return string 3071 */ 3072 protected function endBoundary($boundary) 3073 { 3074 return static::$LE . '--' . $boundary . '--' . static::$LE; 3075 } 3076 3077 /** 3078 * Set the message type. 3079 * PHPMailer only supports some preset message types, not arbitrary MIME structures. 3080 */ 3081 protected function setMessageType() 3082 { 3083 $type = []; 3084 if ($this->alternativeExists()) { 3085 $type[] = 'alt'; 3086 } 3087 if ($this->inlineImageExists()) { 3088 $type[] = 'inline'; 3089 } 3090 if ($this->attachmentExists()) { 3091 $type[] = 'attach'; 3092 } 3093 $this->message_type = implode('_', $type); 3094 if ('' === $this->message_type) { 3095 //The 'plain' message_type refers to the message having a single body element, not that it is plain-text 3096 $this->message_type = 'plain'; 3097 } 3098 } 3099 3100 /** 3101 * Format a header line. 3102 * 3103 * @param string $name 3104 * @param string|int $value 3105 * 3106 * @return string 3107 */ 3108 public function headerLine($name, $value) 3109 { 3110 return $name . ': ' . $value . static::$LE; 3111 } 3112 3113 /** 3114 * Return a formatted mail line. 3115 * 3116 * @param string $value 3117 * 3118 * @return string 3119 */ 3120 public function textLine($value) 3121 { 3122 return $value . static::$LE; 3123 } 3124 3125 /** 3126 * Add an attachment from a path on the filesystem. 3127 * Never use a user-supplied path to a file! 3128 * Returns false if the file could not be found or read. 3129 * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client. 3130 * If you need to do that, fetch the resource yourself and pass it in via a local file or string. 3131 * 3132 * @param string $path Path to the attachment 3133 * @param string $name Overrides the attachment name 3134 * @param string $encoding File encoding (see $Encoding) 3135 * @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified 3136 * @param string $disposition Disposition to use 3137 * 3138 * @throws Exception 3139 * 3140 * @return bool 3141 */ 3142 public function addAttachment( 3143 $path, 3144 $name = '', 3145 $encoding = self::ENCODING_BASE64, 3146 $type = '', 3147 $disposition = 'attachment' 3148 ) { 3149 try { 3150 if (!static::fileIsAccessible($path)) { 3151 throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); 3152 } 3153 3154 //If a MIME type is not specified, try to work it out from the file name 3155 if ('' === $type) { 3156 $type = static::filenameToType($path); 3157 } 3158 3159 $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); 3160 if ('' === $name) { 3161 $name = $filename; 3162 } 3163 if (!$this->validateEncoding($encoding)) { 3164 throw new Exception($this->lang('encoding') . $encoding); 3165 } 3166 3167 $this->attachment[] = [ 3168 0 => $path, 3169 1 => $filename, 3170 2 => $name, 3171 3 => $encoding, 3172 4 => $type, 3173 5 => false, //isStringAttachment 3174 6 => $disposition, 3175 7 => $name, 3176 ]; 3177 } catch (Exception $exc) { 3178 $this->setError($exc->getMessage()); 3179 $this->edebug($exc->getMessage()); 3180 if ($this->exceptions) { 3181 throw $exc; 3182 } 3183 3184 return false; 3185 } 3186 3187 return true; 3188 } 3189 3190 /** 3191 * Return the array of attachments. 3192 * 3193 * @return array 3194 */ 3195 public function getAttachments() 3196 { 3197 return $this->attachment; 3198 } 3199 3200 /** 3201 * Attach all file, string, and binary attachments to the message. 3202 * Returns an empty string on failure. 3203 * 3204 * @param string $disposition_type 3205 * @param string $boundary 3206 * 3207 * @throws Exception 3208 * 3209 * @return string 3210 */ 3211 protected function attachAll($disposition_type, $boundary) 3212 { 3213 //Return text of body 3214 $mime = []; 3215 $cidUniq = []; 3216 $incl = []; 3217 3218 //Add all attachments 3219 foreach ($this->attachment as $attachment) { 3220 //Check if it is a valid disposition_filter 3221 if ($attachment[6] === $disposition_type) { 3222 //Check for string attachment 3223 $string = ''; 3224 $path = ''; 3225 $bString = $attachment[5]; 3226 if ($bString) { 3227 $string = $attachment[0]; 3228 } else { 3229 $path = $attachment[0]; 3230 } 3231 3232 $inclhash = hash('sha256', serialize($attachment)); 3233 if (in_array($inclhash, $incl, true)) { 3234 continue; 3235 } 3236 $incl[] = $inclhash; 3237 $name = $attachment[2]; 3238 $encoding = $attachment[3]; 3239 $type = $attachment[4]; 3240 $disposition = $attachment[6]; 3241 $cid = $attachment[7]; 3242 if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) { 3243 continue; 3244 } 3245 $cidUniq[$cid] = true; 3246 3247 $mime[] = sprintf('--%s%s', $boundary, static::$LE); 3248 //Only include a filename property if we have one 3249 if (!empty($name)) { 3250 $mime[] = sprintf( 3251 'Content-Type: %s; name=%s%s', 3252 $type, 3253 static::quotedString($this->encodeHeader($this->secureHeader($name))), 3254 static::$LE 3255 ); 3256 } else { 3257 $mime[] = sprintf( 3258 'Content-Type: %s%s', 3259 $type, 3260 static::$LE 3261 ); 3262 } 3263 //RFC1341 part 5 says 7bit is assumed if not specified 3264 if (static::ENCODING_7BIT !== $encoding) { 3265 $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE); 3266 } 3267 3268 //Only set Content-IDs on inline attachments 3269 if ((string) $cid !== '' && $disposition === 'inline') { 3270 $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE; 3271 } 3272 3273 //Allow for bypassing the Content-Disposition header 3274 if (!empty($disposition)) { 3275 $encoded_name = $this->encodeHeader($this->secureHeader($name)); 3276 if (!empty($encoded_name)) { 3277 $mime[] = sprintf( 3278 'Content-Disposition: %s; filename=%s%s', 3279 $disposition, 3280 static::quotedString($encoded_name), 3281 static::$LE . static::$LE 3282 ); 3283 } else { 3284 $mime[] = sprintf( 3285 'Content-Disposition: %s%s', 3286 $disposition, 3287 static::$LE . static::$LE 3288 ); 3289 } 3290 } else { 3291 $mime[] = static::$LE; 3292 } 3293 3294 //Encode as string attachment 3295 if ($bString) { 3296 $mime[] = $this->encodeString($string, $encoding); 3297 } else { 3298 $mime[] = $this->encodeFile($path, $encoding); 3299 } 3300 if ($this->isError()) { 3301 return ''; 3302 } 3303 $mime[] = static::$LE; 3304 } 3305 } 3306 3307 $mime[] = sprintf('--%s--%s', $boundary, static::$LE); 3308 3309 return implode('', $mime); 3310 } 3311 3312 /** 3313 * Encode a file attachment in requested format. 3314 * Returns an empty string on failure. 3315 * 3316 * @param string $path The full path to the file 3317 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' 3318 * 3319 * @return string 3320 */ 3321 protected function encodeFile($path, $encoding = self::ENCODING_BASE64) 3322 { 3323 try { 3324 if (!static::fileIsAccessible($path)) { 3325 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); 3326 } 3327 $file_buffer = file_get_contents($path); 3328 if (false === $file_buffer) { 3329 throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); 3330 } 3331 $file_buffer = $this->encodeString($file_buffer, $encoding); 3332 3333 return $file_buffer; 3334 } catch (Exception $exc) { 3335 $this->setError($exc->getMessage()); 3336 $this->edebug($exc->getMessage()); 3337 if ($this->exceptions) { 3338 throw $exc; 3339 } 3340 3341 return ''; 3342 } 3343 } 3344 3345 /** 3346 * Encode a string in requested format. 3347 * Returns an empty string on failure. 3348 * 3349 * @param string $str The text to encode 3350 * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' 3351 * 3352 * @throws Exception 3353 * 3354 * @return string 3355 */ 3356 public function encodeString($str, $encoding = self::ENCODING_BASE64) 3357 { 3358 $encoded = ''; 3359 switch (strtolower($encoding)) { 3360 case static::ENCODING_BASE64: 3361 $encoded = chunk_split( 3362 base64_encode($str), 3363 static::STD_LINE_LENGTH, 3364 static::$LE 3365 ); 3366 break; 3367 case static::ENCODING_7BIT: 3368 case static::ENCODING_8BIT: 3369 $encoded = static::normalizeBreaks($str); 3370 //Make sure it ends with a line break 3371 if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) { 3372 $encoded .= static::$LE; 3373 } 3374 break; 3375 case static::ENCODING_BINARY: 3376 $encoded = $str; 3377 break; 3378 case static::ENCODING_QUOTED_PRINTABLE: 3379 $encoded = $this->encodeQP($str); 3380 break; 3381 default: 3382 $this->setError($this->lang('encoding') . $encoding); 3383 if ($this->exceptions) { 3384 throw new Exception($this->lang('encoding') . $encoding); 3385 } 3386 break; 3387 } 3388 3389 return $encoded; 3390 } 3391 3392 /** 3393 * Encode a header value (not including its label) optimally. 3394 * Picks shortest of Q, B, or none. Result includes folding if needed. 3395 * See RFC822 definitions for phrase, comment and text positions. 3396 * 3397 * @param string $str The header value to encode 3398 * @param string $position What context the string will be used in 3399 * 3400 * @return string 3401 */ 3402 public function encodeHeader($str, $position = 'text') 3403 { 3404 $matchcount = 0; 3405 switch (strtolower($position)) { 3406 case 'phrase': 3407 if (!preg_match('/[\200-\377]/', $str)) { 3408 //Can't use addslashes as we don't know the value of magic_quotes_sybase 3409 $encoded = addcslashes($str, "\0..\37\177\\\""); 3410 if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { 3411 return $encoded; 3412 } 3413 3414 return "\"$encoded\""; 3415 } 3416 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); 3417 break; 3418 /* @noinspection PhpMissingBreakStatementInspection */ 3419 case 'comment': 3420 $matchcount = preg_match_all('/[()"]/', $str, $matches); 3421 //fallthrough 3422 case 'text': 3423 default: 3424 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); 3425 break; 3426 } 3427 3428 if ($this->has8bitChars($str)) { 3429 $charset = $this->CharSet; 3430 } else { 3431 $charset = static::CHARSET_ASCII; 3432 } 3433 3434 //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`"). 3435 $overhead = 8 + strlen($charset); 3436 3437 if ('mail' === $this->Mailer) { 3438 $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead; 3439 } else { 3440 $maxlen = static::MAX_LINE_LENGTH - $overhead; 3441 } 3442 3443 //Select the encoding that produces the shortest output and/or prevents corruption. 3444 if ($matchcount > strlen($str) / 3) { 3445 //More than 1/3 of the content needs encoding, use B-encode. 3446 $encoding = 'B'; 3447 } elseif ($matchcount > 0) { 3448 //Less than 1/3 of the content needs encoding, use Q-encode. 3449 $encoding = 'Q'; 3450 } elseif (strlen($str) > $maxlen) { 3451 //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption. 3452 $encoding = 'Q'; 3453 } else { 3454 //No reformatting needed 3455 $encoding = false; 3456 } 3457 3458 switch ($encoding) { 3459 case 'B': 3460 if ($this->hasMultiBytes($str)) { 3461 //Use a custom function which correctly encodes and wraps long 3462 //multibyte strings without breaking lines within a character 3463 $encoded = $this->base64EncodeWrapMB($str, "\n"); 3464 } else { 3465 $encoded = base64_encode($str); 3466 $maxlen -= $maxlen % 4; 3467 $encoded = trim(chunk_split($encoded, $maxlen, "\n")); 3468 } 3469 $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); 3470 break; 3471 case 'Q': 3472 $encoded = $this->encodeQ($str, $position); 3473 $encoded = $this->wrapText($encoded, $maxlen, true); 3474 $encoded = str_replace('=' . static::$LE, "\n", trim($encoded)); 3475 $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); 3476 break; 3477 default: 3478 return $str; 3479 } 3480 3481 return trim(static::normalizeBreaks($encoded)); 3482 } 3483 3484 /** 3485 * Check if a string contains multi-byte characters. 3486 * 3487 * @param string $str multi-byte text to wrap encode 3488 * 3489 * @return bool 3490 */ 3491 public function hasMultiBytes($str) 3492 { 3493 if (function_exists('mb_strlen')) { 3494 return strlen($str) > mb_strlen($str, $this->CharSet); 3495 } 3496 3497 //Assume no multibytes (we can't handle without mbstring functions anyway) 3498 return false; 3499 } 3500 3501 /** 3502 * Does a string contain any 8-bit chars (in any charset)? 3503 * 3504 * @param string $text 3505 * 3506 * @return bool 3507 */ 3508 public function has8bitChars($text) 3509 { 3510 return (bool) preg_match('/[\x80-\xFF]/', $text); 3511 } 3512 3513 /** 3514 * Encode and wrap long multibyte strings for mail headers 3515 * without breaking lines within a character. 3516 * Adapted from a function by paravoid. 3517 * 3518 * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 3519 * 3520 * @param string $str multi-byte text to wrap encode 3521 * @param string $linebreak string to use as linefeed/end-of-line 3522 * 3523 * @return string 3524 */ 3525 public function base64EncodeWrapMB($str, $linebreak = null) 3526 { 3527 $start = '=?' . $this->CharSet . '?B?'; 3528 $end = '?='; 3529 $encoded = ''; 3530 if (null === $linebreak) { 3531 $linebreak = static::$LE; 3532 } 3533 3534 $mb_length = mb_strlen($str, $this->CharSet); 3535 //Each line must have length <= 75, including $start and $end 3536 $length = 75 - strlen($start) - strlen($end); 3537 //Average multi-byte ratio 3538 $ratio = $mb_length / strlen($str); 3539 //Base64 has a 4:3 ratio 3540 $avgLength = floor($length * $ratio * .75); 3541 3542 $offset = 0; 3543 for ($i = 0; $i < $mb_length; $i += $offset) { 3544 $lookBack = 0; 3545 do { 3546 $offset = $avgLength - $lookBack; 3547 $chunk = mb_substr($str, $i, $offset, $this->CharSet); 3548 $chunk = base64_encode($chunk); 3549 ++$lookBack; 3550 } while (strlen($chunk) > $length); 3551 $encoded .= $chunk . $linebreak; 3552 } 3553 3554 //Chomp the last linefeed 3555 return substr($encoded, 0, -strlen($linebreak)); 3556 } 3557 3558 /** 3559 * Encode a string in quoted-printable format. 3560 * According to RFC2045 section 6.7. 3561 * 3562 * @param string $string The text to encode 3563 * 3564 * @return string 3565 */ 3566 public function encodeQP($string) 3567 { 3568 return static::normalizeBreaks(quoted_printable_encode($string)); 3569 } 3570 3571 /** 3572 * Encode a string using Q encoding. 3573 * 3574 * @see http://tools.ietf.org/html/rfc2047#section-4.2 3575 * 3576 * @param string $str the text to encode 3577 * @param string $position Where the text is going to be used, see the RFC for what that means 3578 * 3579 * @return string 3580 */ 3581 public function encodeQ($str, $position = 'text') 3582 { 3583 //There should not be any EOL in the string 3584 $pattern = ''; 3585 $encoded = str_replace(["\r", "\n"], '', $str); 3586 switch (strtolower($position)) { 3587 case 'phrase': 3588 //RFC 2047 section 5.3 3589 $pattern = '^A-Za-z0-9!*+\/ -'; 3590 break; 3591 /* 3592 * RFC 2047 section 5.2. 3593 * Build $pattern without including delimiters and [] 3594 */ 3595 /* @noinspection PhpMissingBreakStatementInspection */ 3596 case 'comment': 3597 $pattern = '\(\)"'; 3598 /* Intentional fall through */ 3599 case 'text': 3600 default: 3601 //RFC 2047 section 5.1 3602 //Replace every high ascii, control, =, ? and _ characters 3603 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; 3604 break; 3605 } 3606 $matches = []; 3607 if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { 3608 //If the string contains an '=', make sure it's the first thing we replace 3609 //so as to avoid double-encoding 3610 $eqkey = array_search('=', $matches[0], true); 3611 if (false !== $eqkey) { 3612 unset($matches[0][$eqkey]); 3613 array_unshift($matches[0], '='); 3614 } 3615 foreach (array_unique($matches[0]) as $char) { 3616 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); 3617 } 3618 } 3619 //Replace spaces with _ (more readable than =20) 3620 //RFC 2047 section 4.2(2) 3621 return str_replace(' ', '_', $encoded); 3622 } 3623 3624 /** 3625 * Add a string or binary attachment (non-filesystem). 3626 * This method can be used to attach ascii or binary data, 3627 * such as a BLOB record from a database. 3628 * 3629 * @param string $string String attachment data 3630 * @param string $filename Name of the attachment 3631 * @param string $encoding File encoding (see $Encoding) 3632 * @param string $type File extension (MIME) type 3633 * @param string $disposition Disposition to use 3634 * 3635 * @throws Exception 3636 * 3637 * @return bool True on successfully adding an attachment 3638 */ 3639 public function addStringAttachment( 3640 $string, 3641 $filename, 3642 $encoding = self::ENCODING_BASE64, 3643 $type = '', 3644 $disposition = 'attachment' 3645 ) { 3646 try { 3647 //If a MIME type is not specified, try to work it out from the file name 3648 if ('' === $type) { 3649 $type = static::filenameToType($filename); 3650 } 3651 3652 if (!$this->validateEncoding($encoding)) { 3653 throw new Exception($this->lang('encoding') . $encoding); 3654 } 3655 3656 //Append to $attachment array 3657 $this->attachment[] = [ 3658 0 => $string, 3659 1 => $filename, 3660 2 => static::mb_pathinfo($filename, PATHINFO_BASENAME), 3661 3 => $encoding, 3662 4 => $type, 3663 5 => true, //isStringAttachment 3664 6 => $disposition, 3665 7 => 0, 3666 ]; 3667 } catch (Exception $exc) { 3668 $this->setError($exc->getMessage()); 3669 $this->edebug($exc->getMessage()); 3670 if ($this->exceptions) { 3671 throw $exc; 3672 } 3673 3674 return false; 3675 } 3676 3677 return true; 3678 } 3679 3680 /** 3681 * Add an embedded (inline) attachment from a file. 3682 * This can include images, sounds, and just about any other document type. 3683 * These differ from 'regular' attachments in that they are intended to be 3684 * displayed inline with the message, not just attached for download. 3685 * This is used in HTML messages that embed the images 3686 * the HTML refers to using the $cid value. 3687 * Never use a user-supplied path to a file! 3688 * 3689 * @param string $path Path to the attachment 3690 * @param string $cid Content ID of the attachment; Use this to reference 3691 * the content when using an embedded image in HTML 3692 * @param string $name Overrides the attachment name 3693 * @param string $encoding File encoding (see $Encoding) 3694 * @param string $type File MIME type 3695 * @param string $disposition Disposition to use 3696 * 3697 * @throws Exception 3698 * 3699 * @return bool True on successfully adding an attachment 3700 */ 3701 public function addEmbeddedImage( 3702 $path, 3703 $cid, 3704 $name = '', 3705 $encoding = self::ENCODING_BASE64, 3706 $type = '', 3707 $disposition = 'inline' 3708 ) { 3709 try { 3710 if (!static::fileIsAccessible($path)) { 3711 throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); 3712 } 3713 3714 //If a MIME type is not specified, try to work it out from the file name 3715 if ('' === $type) { 3716 $type = static::filenameToType($path); 3717 } 3718 3719 if (!$this->validateEncoding($encoding)) { 3720 throw new Exception($this->lang('encoding') . $encoding); 3721 } 3722 3723 $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); 3724 if ('' === $name) { 3725 $name = $filename; 3726 } 3727 3728 //Append to $attachment array 3729 $this->attachment[] = [ 3730 0 => $path, 3731 1 => $filename, 3732 2 => $name, 3733 3 => $encoding, 3734 4 => $type, 3735 5 => false, //isStringAttachment 3736 6 => $disposition, 3737 7 => $cid, 3738 ]; 3739 } catch (Exception $exc) { 3740 $this->setError($exc->getMessage()); 3741 $this->edebug($exc->getMessage()); 3742 if ($this->exceptions) { 3743 throw $exc; 3744 } 3745 3746 return false; 3747 } 3748 3749 return true; 3750 } 3751 3752 /** 3753 * Add an embedded stringified attachment. 3754 * This can include images, sounds, and just about any other document type. 3755 * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type. 3756 * 3757 * @param string $string The attachment binary data 3758 * @param string $cid Content ID of the attachment; Use this to reference 3759 * the content when using an embedded image in HTML 3760 * @param string $name A filename for the attachment. If this contains an extension, 3761 * PHPMailer will attempt to set a MIME type for the attachment. 3762 * For example 'file.jpg' would get an 'image/jpeg' MIME type. 3763 * @param string $encoding File encoding (see $Encoding), defaults to 'base64' 3764 * @param string $type MIME type - will be used in preference to any automatically derived type 3765 * @param string $disposition Disposition to use 3766 * 3767 * @throws Exception 3768 * 3769 * @return bool True on successfully adding an attachment 3770 */ 3771 public function addStringEmbeddedImage( 3772 $string, 3773 $cid, 3774 $name = '', 3775 $encoding = self::ENCODING_BASE64, 3776 $type = '', 3777 $disposition = 'inline' 3778 ) { 3779 try { 3780 //If a MIME type is not specified, try to work it out from the name 3781 if ('' === $type && !empty($name)) { 3782 $type = static::filenameToType($name); 3783 } 3784 3785 if (!$this->validateEncoding($encoding)) { 3786 throw new Exception($this->lang('encoding') . $encoding); 3787 } 3788 3789 //Append to $attachment array 3790 $this->attachment[] = [ 3791 0 => $string, 3792 1 => $name, 3793 2 => $name, 3794 3 => $encoding, 3795 4 => $type, 3796 5 => true, //isStringAttachment 3797 6 => $disposition, 3798 7 => $cid, 3799 ]; 3800 } catch (Exception $exc) { 3801 $this->setError($exc->getMessage()); 3802 $this->edebug($exc->getMessage()); 3803 if ($this->exceptions) { 3804 throw $exc; 3805 } 3806 3807 return false; 3808 } 3809 3810 return true; 3811 } 3812 3813 /** 3814 * Validate encodings. 3815 * 3816 * @param string $encoding 3817 * 3818 * @return bool 3819 */ 3820 protected function validateEncoding($encoding) 3821 { 3822 return in_array( 3823 $encoding, 3824 [ 3825 self::ENCODING_7BIT, 3826 self::ENCODING_QUOTED_PRINTABLE, 3827 self::ENCODING_BASE64, 3828 self::ENCODING_8BIT, 3829 self::ENCODING_BINARY, 3830 ], 3831 true 3832 ); 3833 } 3834 3835 /** 3836 * Check if an embedded attachment is present with this cid. 3837 * 3838 * @param string $cid 3839 * 3840 * @return bool 3841 */ 3842 protected function cidExists($cid) 3843 { 3844 foreach ($this->attachment as $attachment) { 3845 if ('inline' === $attachment[6] && $cid === $attachment[7]) { 3846 return true; 3847 } 3848 } 3849 3850 return false; 3851 } 3852 3853 /** 3854 * Check if an inline attachment is present. 3855 * 3856 * @return bool 3857 */ 3858 public function inlineImageExists() 3859 { 3860 foreach ($this->attachment as $attachment) { 3861 if ('inline' === $attachment[6]) { 3862 return true; 3863 } 3864 } 3865 3866 return false; 3867 } 3868 3869 /** 3870 * Check if an attachment (non-inline) is present. 3871 * 3872 * @return bool 3873 */ 3874 public function attachmentExists() 3875 { 3876 foreach ($this->attachment as $attachment) { 3877 if ('attachment' === $attachment[6]) { 3878 return true; 3879 } 3880 } 3881 3882 return false; 3883 } 3884 3885 /** 3886 * Check if this message has an alternative body set. 3887 * 3888 * @return bool 3889 */ 3890 public function alternativeExists() 3891 { 3892 return !empty($this->AltBody); 3893 } 3894 3895 /** 3896 * Clear queued addresses of given kind. 3897 * 3898 * @param string $kind 'to', 'cc', or 'bcc' 3899 */ 3900 public function clearQueuedAddresses($kind) 3901 { 3902 $this->RecipientsQueue = array_filter( 3903 $this->RecipientsQueue, 3904 static function ($params) use ($kind) { 3905 return $params[0] !== $kind; 3906 } 3907 ); 3908 } 3909 3910 /** 3911 * Clear all To recipients. 3912 */ 3913 public function clearAddresses() 3914 { 3915 foreach ($this->to as $to) { 3916 unset($this->all_recipients[strtolower($to[0])]); 3917 } 3918 $this->to = []; 3919 $this->clearQueuedAddresses('to'); 3920 } 3921 3922 /** 3923 * Clear all CC recipients. 3924 */ 3925 public function clearCCs() 3926 { 3927 foreach ($this->cc as $cc) { 3928 unset($this->all_recipients[strtolower($cc[0])]); 3929 } 3930 $this->cc = []; 3931 $this->clearQueuedAddresses('cc'); 3932 } 3933 3934 /** 3935 * Clear all BCC recipients. 3936 */ 3937 public function clearBCCs() 3938 { 3939 foreach ($this->bcc as $bcc) { 3940 unset($this->all_recipients[strtolower($bcc[0])]); 3941 } 3942 $this->bcc = []; 3943 $this->clearQueuedAddresses('bcc'); 3944 } 3945 3946 /** 3947 * Clear all ReplyTo recipients. 3948 */ 3949 public function clearReplyTos() 3950 { 3951 $this->ReplyTo = []; 3952 $this->ReplyToQueue = []; 3953 } 3954 3955 /** 3956 * Clear all recipient types. 3957 */ 3958 public function clearAllRecipients() 3959 { 3960 $this->to = []; 3961 $this->cc = []; 3962 $this->bcc = []; 3963 $this->all_recipients = []; 3964 $this->RecipientsQueue = []; 3965 } 3966 3967 /** 3968 * Clear all filesystem, string, and binary attachments. 3969 */ 3970 public function clearAttachments() 3971 { 3972 $this->attachment = []; 3973 } 3974 3975 /** 3976 * Clear all custom headers. 3977 */ 3978 public function clearCustomHeaders() 3979 { 3980 $this->CustomHeader = []; 3981 } 3982 3983 /** 3984 * Add an error message to the error container. 3985 * 3986 * @param string $msg 3987 */ 3988 protected function setError($msg) 3989 { 3990 ++$this->error_count; 3991 if ('smtp' === $this->Mailer && null !== $this->smtp) { 3992 $lasterror = $this->smtp->getError(); 3993 if (!empty($lasterror['error'])) { 3994 $msg .= $this->lang('smtp_error') . $lasterror['error']; 3995 if (!empty($lasterror['detail'])) { 3996 $msg .= ' ' . $this->lang('smtp_detail') . $lasterror['detail']; 3997 } 3998 if (!empty($lasterror['smtp_code'])) { 3999 $msg .= ' ' . $this->lang('smtp_code') . $lasterror['smtp_code']; 4000 } 4001 if (!empty($lasterror['smtp_code_ex'])) { 4002 $msg .= ' ' . $this->lang('smtp_code_ex') . $lasterror['smtp_code_ex']; 4003 } 4004 } 4005 } 4006 $this->ErrorInfo = $msg; 4007 } 4008 4009 /** 4010 * Return an RFC 822 formatted date. 4011 * 4012 * @return string 4013 */ 4014 public static function rfcDate() 4015 { 4016 //Set the time zone to whatever the default is to avoid 500 errors 4017 //Will default to UTC if it's not set properly in php.ini 4018 date_default_timezone_set(@date_default_timezone_get()); 4019 4020 return date('D, j M Y H:i:s O'); 4021 } 4022 4023 /** 4024 * Get the server hostname. 4025 * Returns 'localhost.localdomain' if unknown. 4026 * 4027 * @return string 4028 */ 4029 protected function serverHostname() 4030 { 4031 $result = ''; 4032 if (!empty($this->Hostname)) { 4033 $result = $this->Hostname; 4034 } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) { 4035 $result = $_SERVER['SERVER_NAME']; 4036 } elseif (function_exists('gethostname') && gethostname() !== false) { 4037 $result = gethostname(); 4038 } elseif (php_uname('n') !== false) { 4039 $result = php_uname('n'); 4040 } 4041 if (!static::isValidHost($result)) { 4042 return 'localhost.localdomain'; 4043 } 4044 4045 return $result; 4046 } 4047 4048 /** 4049 * Validate whether a string contains a valid value to use as a hostname or IP address. 4050 * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`. 4051 * 4052 * @param string $host The host name or IP address to check 4053 * 4054 * @return bool 4055 */ 4056 public static function isValidHost($host) 4057 { 4058 //Simple syntax limits 4059 if ( 4060 empty($host) 4061 || !is_string($host) 4062 || strlen($host) > 256 4063 || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+\])$/', $host) 4064 ) { 4065 return false; 4066 } 4067 //Looks like a bracketed IPv6 address 4068 if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') { 4069 return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; 4070 } 4071 //If removing all the dots results in a numeric string, it must be an IPv4 address. 4072 //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names 4073 if (is_numeric(str_replace('.', '', $host))) { 4074 //Is it a valid IPv4 address? 4075 return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; 4076 } 4077 if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) { 4078 //Is it a syntactically valid hostname? 4079 return true; 4080 } 4081 4082 return false; 4083 } 4084 4085 /** 4086 * Get an error message in the current language. 4087 * 4088 * @param string $key 4089 * 4090 * @return string 4091 */ 4092 protected function lang($key) 4093 { 4094 if (count($this->language) < 1) { 4095 $this->setLanguage(); //Set the default language 4096 } 4097 4098 if (array_key_exists($key, $this->language)) { 4099 if ('smtp_connect_failed' === $key) { 4100 //Include a link to troubleshooting docs on SMTP connection failure. 4101 //This is by far the biggest cause of support questions 4102 //but it's usually not PHPMailer's fault. 4103 return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; 4104 } 4105 4106 return $this->language[$key]; 4107 } 4108 4109 //Return the key as a fallback 4110 return $key; 4111 } 4112 4113 /** 4114 * Check if an error occurred. 4115 * 4116 * @return bool True if an error did occur 4117 */ 4118 public function isError() 4119 { 4120 return $this->error_count > 0; 4121 } 4122 4123 /** 4124 * Add a custom header. 4125 * $name value can be overloaded to contain 4126 * both header name and value (name:value). 4127 * 4128 * @param string $name Custom header name 4129 * @param string|null $value Header value 4130 * 4131 * @throws Exception 4132 */ 4133 public function addCustomHeader($name, $value = null) 4134 { 4135 if (null === $value && strpos($name, ':') !== false) { 4136 //Value passed in as name:value 4137 list($name, $value) = explode(':', $name, 2); 4138 } 4139 $name = trim($name); 4140 $value = (null === $value) ? '' : trim($value); 4141 //Ensure name is not empty, and that neither name nor value contain line breaks 4142 if (empty($name) || strpbrk($name . $value, "\r\n") !== false) { 4143 if ($this->exceptions) { 4144 throw new Exception($this->lang('invalid_header')); 4145 } 4146 4147 return false; 4148 } 4149 $this->CustomHeader[] = [$name, $value]; 4150 4151 return true; 4152 } 4153 4154 /** 4155 * Returns all custom headers. 4156 * 4157 * @return array 4158 */ 4159 public function getCustomHeaders() 4160 { 4161 return $this->CustomHeader; 4162 } 4163 4164 /** 4165 * Create a message body from an HTML string. 4166 * Automatically inlines images and creates a plain-text version by converting the HTML, 4167 * overwriting any existing values in Body and AltBody. 4168 * Do not source $message content from user input! 4169 * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty 4170 * will look for an image file in $basedir/images/a.png and convert it to inline. 4171 * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) 4172 * Converts data-uri images into embedded attachments. 4173 * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. 4174 * 4175 * @param string $message HTML message string 4176 * @param string $basedir Absolute path to a base directory to prepend to relative paths to images 4177 * @param bool|callable $advanced Whether to use the internal HTML to text converter 4178 * or your own custom converter 4179 * @return string The transformed message body 4180 * 4181 * @throws Exception 4182 * 4183 * @see PHPMailer::html2text() 4184 */ 4185 public function msgHTML($message, $basedir = '', $advanced = false) 4186 { 4187 preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images); 4188 if (array_key_exists(2, $images)) { 4189 if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { 4190 //Ensure $basedir has a trailing / 4191 $basedir .= '/'; 4192 } 4193 foreach ($images[2] as $imgindex => $url) { 4194 //Convert data URIs into embedded images 4195 //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" 4196 $match = []; 4197 if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) { 4198 if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) { 4199 $data = base64_decode($match[3]); 4200 } elseif ('' === $match[2]) { 4201 $data = rawurldecode($match[3]); 4202 } else { 4203 //Not recognised so leave it alone 4204 continue; 4205 } 4206 //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places 4207 //will only be embedded once, even if it used a different encoding 4208 $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2 4209 4210 if (!$this->cidExists($cid)) { 4211 $this->addStringEmbeddedImage( 4212 $data, 4213 $cid, 4214 'embed' . $imgindex, 4215 static::ENCODING_BASE64, 4216 $match[1] 4217 ); 4218 } 4219 $message = str_replace( 4220 $images[0][$imgindex], 4221 $images[1][$imgindex] . '="cid:' . $cid . '"', 4222 $message 4223 ); 4224 continue; 4225 } 4226 if ( 4227 //Only process relative URLs if a basedir is provided (i.e. no absolute local paths) 4228 !empty($basedir) 4229 //Ignore URLs containing parent dir traversal (..) 4230 && (strpos($url, '..') === false) 4231 //Do not change urls that are already inline images 4232 && 0 !== strpos($url, 'cid:') 4233 //Do not change absolute URLs, including anonymous protocol 4234 && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) 4235 ) { 4236 $filename = static::mb_pathinfo($url, PATHINFO_BASENAME); 4237 $directory = dirname($url); 4238 if ('.' === $directory) { 4239 $directory = ''; 4240 } 4241 //RFC2392 S 2 4242 $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0'; 4243 if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { 4244 $basedir .= '/'; 4245 } 4246 if (strlen($directory) > 1 && '/' !== substr($directory, -1)) { 4247 $directory .= '/'; 4248 } 4249 if ( 4250 $this->addEmbeddedImage( 4251 $basedir . $directory . $filename, 4252 $cid, 4253 $filename, 4254 static::ENCODING_BASE64, 4255 static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION)) 4256 ) 4257 ) { 4258 $message = preg_replace( 4259 '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', 4260 $images[1][$imgindex] . '="cid:' . $cid . '"', 4261 $message 4262 ); 4263 } 4264 } 4265 } 4266 } 4267 $this->isHTML(); 4268 //Convert all message body line breaks to LE, makes quoted-printable encoding work much better 4269 $this->Body = static::normalizeBreaks($message); 4270 $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced)); 4271 if (!$this->alternativeExists()) { 4272 $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.' 4273 . static::$LE; 4274 } 4275 4276 return $this->Body; 4277 } 4278 4279 /** 4280 * Convert an HTML string into plain text. 4281 * This is used by msgHTML(). 4282 * Note - older versions of this function used a bundled advanced converter 4283 * which was removed for license reasons in #232. 4284 * Example usage: 4285 * 4286 * ```php 4287 * //Use default conversion 4288 * $plain = $mail->html2text($html); 4289 * //Use your own custom converter 4290 * $plain = $mail->html2text($html, function($html) { 4291 * $converter = new MyHtml2text($html); 4292 * return $converter->get_text(); 4293 * }); 4294 * ``` 4295 * 4296 * @param string $html The HTML text to convert 4297 * @param bool|callable $advanced Any boolean value to use the internal converter, 4298 * or provide your own callable for custom conversion. 4299 * *Never* pass user-supplied data into this parameter 4300 * 4301 * @return string 4302 */ 4303 public function html2text($html, $advanced = false) 4304 { 4305 if (is_callable($advanced)) { 4306 return call_user_func($advanced, $html); 4307 } 4308 4309 return html_entity_decode( 4310 trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), 4311 ENT_QUOTES, 4312 $this->CharSet 4313 ); 4314 } 4315 4316 /** 4317 * Get the MIME type for a file extension. 4318 * 4319 * @param string $ext File extension 4320 * 4321 * @return string MIME type of file 4322 */ 4323 public static function _mime_types($ext = '') 4324 { 4325 $mimes = [ 4326 'xl' => 'application/excel', 4327 'js' => 'application/javascript', 4328 'hqx' => 'application/mac-binhex40', 4329 'cpt' => 'application/mac-compactpro', 4330 'bin' => 'application/macbinary', 4331 'doc' => 'application/msword', 4332 'word' => 'application/msword', 4333 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 4334 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 4335 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 4336 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 4337 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 4338 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 4339 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 4340 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 4341 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', 4342 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 4343 'class' => 'application/octet-stream', 4344 'dll' => 'application/octet-stream', 4345 'dms' => 'application/octet-stream', 4346 'exe' => 'application/octet-stream', 4347 'lha' => 'application/octet-stream', 4348 'lzh' => 'application/octet-stream', 4349 'psd' => 'application/octet-stream', 4350 'sea' => 'application/octet-stream', 4351 'so' => 'application/octet-stream', 4352 'oda' => 'application/oda', 4353 'pdf' => 'application/pdf', 4354 'ai' => 'application/postscript', 4355 'eps' => 'application/postscript', 4356 'ps' => 'application/postscript', 4357 'smi' => 'application/smil', 4358 'smil' => 'application/smil', 4359 'mif' => 'application/vnd.mif', 4360 'xls' => 'application/vnd.ms-excel', 4361 'ppt' => 'application/vnd.ms-powerpoint', 4362 'wbxml' => 'application/vnd.wap.wbxml', 4363 'wmlc' => 'application/vnd.wap.wmlc', 4364 'dcr' => 'application/x-director', 4365 'dir' => 'application/x-director', 4366 'dxr' => 'application/x-director', 4367 'dvi' => 'application/x-dvi', 4368 'gtar' => 'application/x-gtar', 4369 'php3' => 'application/x-httpd-php', 4370 'php4' => 'application/x-httpd-php', 4371 'php' => 'application/x-httpd-php', 4372 'phtml' => 'application/x-httpd-php', 4373 'phps' => 'application/x-httpd-php-source', 4374 'swf' => 'application/x-shockwave-flash', 4375 'sit' => 'application/x-stuffit', 4376 'tar' => 'application/x-tar', 4377 'tgz' => 'application/x-tar', 4378 'xht' => 'application/xhtml+xml', 4379 'xhtml' => 'application/xhtml+xml', 4380 'zip' => 'application/zip', 4381 'mid' => 'audio/midi', 4382 'midi' => 'audio/midi', 4383 'mp2' => 'audio/mpeg', 4384 'mp3' => 'audio/mpeg', 4385 'm4a' => 'audio/mp4', 4386 'mpga' => 'audio/mpeg', 4387 'aif' => 'audio/x-aiff', 4388 'aifc' => 'audio/x-aiff', 4389 'aiff' => 'audio/x-aiff', 4390 'ram' => 'audio/x-pn-realaudio', 4391 'rm' => 'audio/x-pn-realaudio', 4392 'rpm' => 'audio/x-pn-realaudio-plugin', 4393 'ra' => 'audio/x-realaudio', 4394 'wav' => 'audio/x-wav', 4395 'mka' => 'audio/x-matroska', 4396 'bmp' => 'image/bmp', 4397 'gif' => 'image/gif', 4398 'jpeg' => 'image/jpeg', 4399 'jpe' => 'image/jpeg', 4400 'jpg' => 'image/jpeg', 4401 'png' => 'image/png', 4402 'tiff' => 'image/tiff', 4403 'tif' => 'image/tiff', 4404 'webp' => 'image/webp', 4405 'avif' => 'image/avif', 4406 'heif' => 'image/heif', 4407 'heifs' => 'image/heif-sequence', 4408 'heic' => 'image/heic', 4409 'heics' => 'image/heic-sequence', 4410 'eml' => 'message/rfc822', 4411 'css' => 'text/css', 4412 'html' => 'text/html', 4413 'htm' => 'text/html', 4414 'shtml' => 'text/html', 4415 'log' => 'text/plain', 4416 'text' => 'text/plain', 4417 'txt' => 'text/plain', 4418 'rtx' => 'text/richtext', 4419 'rtf' => 'text/rtf', 4420 'vcf' => 'text/vcard', 4421 'vcard' => 'text/vcard', 4422 'ics' => 'text/calendar', 4423 'xml' => 'text/xml', 4424 'xsl' => 'text/xml', 4425 'wmv' => 'video/x-ms-wmv', 4426 'mpeg' => 'video/mpeg', 4427 'mpe' => 'video/mpeg', 4428 'mpg' => 'video/mpeg', 4429 'mp4' => 'video/mp4', 4430 'm4v' => 'video/mp4', 4431 'mov' => 'video/quicktime', 4432 'qt' => 'video/quicktime', 4433 'rv' => 'video/vnd.rn-realvideo', 4434 'avi' => 'video/x-msvideo', 4435 'movie' => 'video/x-sgi-movie', 4436 'webm' => 'video/webm', 4437 'mkv' => 'video/x-matroska', 4438 ]; 4439 $ext = strtolower($ext); 4440 if (array_key_exists($ext, $mimes)) { 4441 return $mimes[$ext]; 4442 } 4443 4444 return 'application/octet-stream'; 4445 } 4446 4447 /** 4448 * Map a file name to a MIME type. 4449 * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. 4450 * 4451 * @param string $filename A file name or full path, does not need to exist as a file 4452 * 4453 * @return string 4454 */ 4455 public static function filenameToType($filename) 4456 { 4457 //In case the path is a URL, strip any query string before getting extension 4458 $qpos = strpos($filename, '?'); 4459 if (false !== $qpos) { 4460 $filename = substr($filename, 0, $qpos); 4461 } 4462 $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION); 4463 4464 return static::_mime_types($ext); 4465 } 4466 4467 /** 4468 * Multi-byte-safe pathinfo replacement. 4469 * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe. 4470 * 4471 * @see http://www.php.net/manual/en/function.pathinfo.php#107461 4472 * 4473 * @param string $path A filename or path, does not need to exist as a file 4474 * @param int|string $options Either a PATHINFO_* constant, 4475 * or a string name to return only the specified piece 4476 * 4477 * @return string|array 4478 */ 4479 public static function mb_pathinfo($path, $options = null) 4480 { 4481 $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '']; 4482 $pathinfo = []; 4483 if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) { 4484 if (array_key_exists(1, $pathinfo)) { 4485 $ret['dirname'] = $pathinfo[1]; 4486 } 4487 if (array_key_exists(2, $pathinfo)) { 4488 $ret['basename'] = $pathinfo[2]; 4489 } 4490 if (array_key_exists(5, $pathinfo)) { 4491 $ret['extension'] = $pathinfo[5]; 4492 } 4493 if (array_key_exists(3, $pathinfo)) { 4494 $ret['filename'] = $pathinfo[3]; 4495 } 4496 } 4497 switch ($options) { 4498 case PATHINFO_DIRNAME: 4499 case 'dirname': 4500 return $ret['dirname']; 4501 case PATHINFO_BASENAME: 4502 case 'basename': 4503 return $ret['basename']; 4504 case PATHINFO_EXTENSION: 4505 case 'extension': 4506 return $ret['extension']; 4507 case PATHINFO_FILENAME: 4508 case 'filename': 4509 return $ret['filename']; 4510 default: 4511 return $ret; 4512 } 4513 } 4514 4515 /** 4516 * Set or reset instance properties. 4517 * You should avoid this function - it's more verbose, less efficient, more error-prone and 4518 * harder to debug than setting properties directly. 4519 * Usage Example: 4520 * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);` 4521 * is the same as: 4522 * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`. 4523 * 4524 * @param string $name The property name to set 4525 * @param mixed $value The value to set the property to 4526 * 4527 * @return bool 4528 */ 4529 public function set($name, $value = '') 4530 { 4531 if (property_exists($this, $name)) { 4532 $this->$name = $value; 4533 4534 return true; 4535 } 4536 $this->setError($this->lang('variable_set') . $name); 4537 4538 return false; 4539 } 4540 4541 /** 4542 * Strip newlines to prevent header injection. 4543 * 4544 * @param string $str 4545 * 4546 * @return string 4547 */ 4548 public function secureHeader($str) 4549 { 4550 return trim(str_replace(["\r", "\n"], '', $str)); 4551 } 4552 4553 /** 4554 * Normalize line breaks in a string. 4555 * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. 4556 * Defaults to CRLF (for message bodies) and preserves consecutive breaks. 4557 * 4558 * @param string $text 4559 * @param string $breaktype What kind of line break to use; defaults to static::$LE 4560 * 4561 * @return string 4562 */ 4563 public static function normalizeBreaks($text, $breaktype = null) 4564 { 4565 if (null === $breaktype) { 4566 $breaktype = static::$LE; 4567 } 4568 //Normalise to \n 4569 $text = str_replace([self::CRLF, "\r"], "\n", $text); 4570 //Now convert LE as needed 4571 if ("\n" !== $breaktype) { 4572 $text = str_replace("\n", $breaktype, $text); 4573 } 4574 4575 return $text; 4576 } 4577 4578 /** 4579 * Remove trailing breaks from a string. 4580 * 4581 * @param string $text 4582 * 4583 * @return string The text to remove breaks from 4584 */ 4585 public static function stripTrailingWSP($text) 4586 { 4587 return rtrim($text, " \r\n\t"); 4588 } 4589 4590 /** 4591 * Return the current line break format string. 4592 * 4593 * @return string 4594 */ 4595 public static function getLE() 4596 { 4597 return static::$LE; 4598 } 4599 4600 /** 4601 * Set the line break format string, e.g. "\r\n". 4602 * 4603 * @param string $le 4604 */ 4605 protected static function setLE($le) 4606 { 4607 static::$LE = $le; 4608 } 4609 4610 /** 4611 * Set the public and private key files and password for S/MIME signing. 4612 * 4613 * @param string $cert_filename 4614 * @param string $key_filename 4615 * @param string $key_pass Password for private key 4616 * @param string $extracerts_filename Optional path to chain certificate 4617 */ 4618 public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') 4619 { 4620 $this->sign_cert_file = $cert_filename; 4621 $this->sign_key_file = $key_filename; 4622 $this->sign_key_pass = $key_pass; 4623 $this->sign_extracerts_file = $extracerts_filename; 4624 } 4625 4626 /** 4627 * Quoted-Printable-encode a DKIM header. 4628 * 4629 * @param string $txt 4630 * 4631 * @return string 4632 */ 4633 public function DKIM_QP($txt) 4634 { 4635 $line = ''; 4636 $len = strlen($txt); 4637 for ($i = 0; $i < $len; ++$i) { 4638 $ord = ord($txt[$i]); 4639 if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { 4640 $line .= $txt[$i]; 4641 } else { 4642 $line .= '=' . sprintf('%02X', $ord); 4643 } 4644 } 4645 4646 return $line; 4647 } 4648 4649 /** 4650 * Generate a DKIM signature. 4651 * 4652 * @param string $signHeader 4653 * 4654 * @throws Exception 4655 * 4656 * @return string The DKIM signature value 4657 */ 4658 public function DKIM_Sign($signHeader) 4659 { 4660 if (!defined('PKCS7_TEXT')) { 4661 if ($this->exceptions) { 4662 throw new Exception($this->lang('extension_missing') . 'openssl'); 4663 } 4664 4665 return ''; 4666 } 4667 $privKeyStr = !empty($this->DKIM_private_string) ? 4668 $this->DKIM_private_string : 4669 file_get_contents($this->DKIM_private); 4670 if ('' !== $this->DKIM_passphrase) { 4671 $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); 4672 } else { 4673 $privKey = openssl_pkey_get_private($privKeyStr); 4674 } 4675 if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { 4676 if (\PHP_MAJOR_VERSION < 8) { 4677 openssl_pkey_free($privKey); 4678 } 4679 4680 return base64_encode($signature); 4681 } 4682 if (\PHP_MAJOR_VERSION < 8) { 4683 openssl_pkey_free($privKey); 4684 } 4685 4686 return ''; 4687 } 4688 4689 /** 4690 * Generate a DKIM canonicalization header. 4691 * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2. 4692 * Canonicalized headers should *always* use CRLF, regardless of mailer setting. 4693 * 4694 * @see https://tools.ietf.org/html/rfc6376#section-3.4.2 4695 * 4696 * @param string $signHeader Header 4697 * 4698 * @return string 4699 */ 4700 public function DKIM_HeaderC($signHeader) 4701 { 4702 //Normalize breaks to CRLF (regardless of the mailer) 4703 $signHeader = static::normalizeBreaks($signHeader, self::CRLF); 4704 //Unfold header lines 4705 //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]` 4706 //@see https://tools.ietf.org/html/rfc5322#section-2.2 4707 //That means this may break if you do something daft like put vertical tabs in your headers. 4708 $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader); 4709 //Break headers out into an array 4710 $lines = explode(self::CRLF, $signHeader); 4711 foreach ($lines as $key => $line) { 4712 //If the header is missing a :, skip it as it's invalid 4713 //This is likely to happen because the explode() above will also split 4714 //on the trailing LE, leaving an empty line 4715 if (strpos($line, ':') === false) { 4716 continue; 4717 } 4718 list($heading, $value) = explode(':', $line, 2); 4719 //Lower-case header name 4720 $heading = strtolower($heading); 4721 //Collapse white space within the value, also convert WSP to space 4722 $value = preg_replace('/[ \t]+/', ' ', $value); 4723 //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value 4724 //But then says to delete space before and after the colon. 4725 //Net result is the same as trimming both ends of the value. 4726 //By elimination, the same applies to the field name 4727 $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t"); 4728 } 4729 4730 return implode(self::CRLF, $lines); 4731 } 4732 4733 /** 4734 * Generate a DKIM canonicalization body. 4735 * Uses the 'simple' algorithm from RFC6376 section 3.4.3. 4736 * Canonicalized bodies should *always* use CRLF, regardless of mailer setting. 4737 * 4738 * @see https://tools.ietf.org/html/rfc6376#section-3.4.3 4739 * 4740 * @param string $body Message Body 4741 * 4742 * @return string 4743 */ 4744 public function DKIM_BodyC($body) 4745 { 4746 if (empty($body)) { 4747 return self::CRLF; 4748 } 4749 //Normalize line endings to CRLF 4750 $body = static::normalizeBreaks($body, self::CRLF); 4751 4752 //Reduce multiple trailing line breaks to a single one 4753 return static::stripTrailingWSP($body) . self::CRLF; 4754 } 4755 4756 /** 4757 * Create the DKIM header and body in a new message header. 4758 * 4759 * @param string $headers_line Header lines 4760 * @param string $subject Subject 4761 * @param string $body Body 4762 * 4763 * @throws Exception 4764 * 4765 * @return string 4766 */ 4767 public function DKIM_Add($headers_line, $subject, $body) 4768 { 4769 $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms 4770 $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body 4771 $DKIMquery = 'dns/txt'; //Query method 4772 $DKIMtime = time(); 4773 //Always sign these headers without being asked 4774 //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1 4775 $autoSignHeaders = [ 4776 'from', 4777 'to', 4778 'cc', 4779 'date', 4780 'subject', 4781 'reply-to', 4782 'message-id', 4783 'content-type', 4784 'mime-version', 4785 'x-mailer', 4786 ]; 4787 if (stripos($headers_line, 'Subject') === false) { 4788 $headers_line .= 'Subject: ' . $subject . static::$LE; 4789 } 4790 $headerLines = explode(static::$LE, $headers_line); 4791 $currentHeaderLabel = ''; 4792 $currentHeaderValue = ''; 4793 $parsedHeaders = []; 4794 $headerLineIndex = 0; 4795 $headerLineCount = count($headerLines); 4796 foreach ($headerLines as $headerLine) { 4797 $matches = []; 4798 if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) { 4799 if ($currentHeaderLabel !== '') { 4800 //We were previously in another header; This is the start of a new header, so save the previous one 4801 $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; 4802 } 4803 $currentHeaderLabel = $matches[1]; 4804 $currentHeaderValue = $matches[2]; 4805 } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) { 4806 //This is a folded continuation of the current header, so unfold it 4807 $currentHeaderValue .= ' ' . $matches[1]; 4808 } 4809 ++$headerLineIndex; 4810 if ($headerLineIndex >= $headerLineCount) { 4811 //This was the last line, so finish off this header 4812 $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; 4813 } 4814 } 4815 $copiedHeaders = []; 4816 $headersToSignKeys = []; 4817 $headersToSign = []; 4818 foreach ($parsedHeaders as $header) { 4819 //Is this header one that must be included in the DKIM signature? 4820 if (in_array(strtolower($header['label']), $autoSignHeaders, true)) { 4821 $headersToSignKeys[] = $header['label']; 4822 $headersToSign[] = $header['label'] . ': ' . $header['value']; 4823 if ($this->DKIM_copyHeaderFields) { 4824 $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC 4825 str_replace('|', '=7C', $this->DKIM_QP($header['value'])); 4826 } 4827 continue; 4828 } 4829 //Is this an extra custom header we've been asked to sign? 4830 if (in_array($header['label'], $this->DKIM_extraHeaders, true)) { 4831 //Find its value in custom headers 4832 foreach ($this->CustomHeader as $customHeader) { 4833 if ($customHeader[0] === $header['label']) { 4834 $headersToSignKeys[] = $header['label']; 4835 $headersToSign[] = $header['label'] . ': ' . $header['value']; 4836 if ($this->DKIM_copyHeaderFields) { 4837 $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC 4838 str_replace('|', '=7C', $this->DKIM_QP($header['value'])); 4839 } 4840 //Skip straight to the next header 4841 continue 2; 4842 } 4843 } 4844 } 4845 } 4846 $copiedHeaderFields = ''; 4847 if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) { 4848 //Assemble a DKIM 'z' tag 4849 $copiedHeaderFields = ' z='; 4850 $first = true; 4851 foreach ($copiedHeaders as $copiedHeader) { 4852 if (!$first) { 4853 $copiedHeaderFields .= static::$LE . ' |'; 4854 } 4855 //Fold long values 4856 if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) { 4857 $copiedHeaderFields .= substr( 4858 chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS), 4859 0, 4860 -strlen(static::$LE . self::FWS) 4861 ); 4862 } else { 4863 $copiedHeaderFields .= $copiedHeader; 4864 } 4865 $first = false; 4866 } 4867 $copiedHeaderFields .= ';' . static::$LE; 4868 } 4869 $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE; 4870 $headerValues = implode(static::$LE, $headersToSign); 4871 $body = $this->DKIM_BodyC($body); 4872 //Base64 of packed binary SHA-256 hash of body 4873 $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); 4874 $ident = ''; 4875 if ('' !== $this->DKIM_identity) { 4876 $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE; 4877 } 4878 //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag 4879 //which is appended after calculating the signature 4880 //https://tools.ietf.org/html/rfc6376#section-3.5 4881 $dkimSignatureHeader = 'DKIM-Signature: v=1;' . 4882 ' d=' . $this->DKIM_domain . ';' . 4883 ' s=' . $this->DKIM_selector . ';' . static::$LE . 4884 ' a=' . $DKIMsignatureType . ';' . 4885 ' q=' . $DKIMquery . ';' . 4886 ' t=' . $DKIMtime . ';' . 4887 ' c=' . $DKIMcanonicalization . ';' . static::$LE . 4888 $headerKeys . 4889 $ident . 4890 $copiedHeaderFields . 4891 ' bh=' . $DKIMb64 . ';' . static::$LE . 4892 ' b='; 4893 //Canonicalize the set of headers 4894 $canonicalizedHeaders = $this->DKIM_HeaderC( 4895 $headerValues . static::$LE . $dkimSignatureHeader 4896 ); 4897 $signature = $this->DKIM_Sign($canonicalizedHeaders); 4898 $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS)); 4899 4900 return static::normalizeBreaks($dkimSignatureHeader . $signature); 4901 } 4902 4903 /** 4904 * Detect if a string contains a line longer than the maximum line length 4905 * allowed by RFC 2822 section 2.1.1. 4906 * 4907 * @param string $str 4908 * 4909 * @return bool 4910 */ 4911 public static function hasLineLongerThanMax($str) 4912 { 4913 return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str); 4914 } 4915 4916 /** 4917 * If a string contains any "special" characters, double-quote the name, 4918 * and escape any double quotes with a backslash. 4919 * 4920 * @param string $str 4921 * 4922 * @return string 4923 * 4924 * @see RFC822 3.4.1 4925 */ 4926 public static function quotedString($str) 4927 { 4928 if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) { 4929 //If the string contains any of these chars, it must be double-quoted 4930 //and any double quotes must be escaped with a backslash 4931 return '"' . str_replace('"', '\\"', $str) . '"'; 4932 } 4933 4934 //Return the string untouched, it doesn't need quoting 4935 return $str; 4936 } 4937 4938 /** 4939 * Allows for public read access to 'to' property. 4940 * Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4941 * 4942 * @return array 4943 */ 4944 public function getToAddresses() 4945 { 4946 return $this->to; 4947 } 4948 4949 /** 4950 * Allows for public read access to 'cc' property. 4951 * Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4952 * 4953 * @return array 4954 */ 4955 public function getCcAddresses() 4956 { 4957 return $this->cc; 4958 } 4959 4960 /** 4961 * Allows for public read access to 'bcc' property. 4962 * Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4963 * 4964 * @return array 4965 */ 4966 public function getBccAddresses() 4967 { 4968 return $this->bcc; 4969 } 4970 4971 /** 4972 * Allows for public read access to 'ReplyTo' property. 4973 * Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4974 * 4975 * @return array 4976 */ 4977 public function getReplyToAddresses() 4978 { 4979 return $this->ReplyTo; 4980 } 4981 4982 /** 4983 * Allows for public read access to 'all_recipients' property. 4984 * Before the send() call, queued addresses (i.e. with IDN) are not yet included. 4985 * 4986 * @return array 4987 */ 4988 public function getAllRecipientAddresses() 4989 { 4990 return $this->all_recipients; 4991 } 4992 4993 /** 4994 * Perform a callback. 4995 * 4996 * @param bool $isSent 4997 * @param array $to 4998 * @param array $cc 4999 * @param array $bcc 5000 * @param string $subject 5001 * @param string $body 5002 * @param string $from 5003 * @param array $extra 5004 */ 5005 protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra) 5006 { 5007 if (!empty($this->action_function) && is_callable($this->action_function)) { 5008 call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra); 5009 } 5010 } 5011 5012 /** 5013 * Get the OAuth instance. 5014 * 5015 * @return OAuth 5016 */ 5017 public function getOAuth() 5018 { 5019 return $this->oauth; 5020 } 5021 5022 /** 5023 * Set an OAuth instance. 5024 */ 5025 public function setOAuth(OAuth $oauth) 5026 { 5027 $this->oauth = $oauth; 5028 } 5029} 5030