[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/PHPMailer/ -> PHPMailer.php (source)

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