You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4820 lines
162 KiB

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