PHPMailer.php

Namespace

PHPMailer\PHPMailer

File

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

Classes

Namesort descending Description
PHPMailer PHPMailer - PHP email creation and transport class.