Email.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Network\Email;
  16. use Cake\Core\App;
  17. use Cake\Core\Configure;
  18. use Cake\Core\StaticConfigTrait;
  19. use Cake\Error\Exception;
  20. use Cake\Log\Log;
  21. use Cake\Network\Error;
  22. use Cake\Network\Http\FormData\Part;
  23. use Cake\Utility\File;
  24. use Cake\Utility\Hash;
  25. use Cake\Utility\String;
  26. use Cake\View\View;
  27. /**
  28. * CakePHP email class.
  29. *
  30. * This class is used for sending Internet Message Format based
  31. * on the standard outlined in http://www.rfc-editor.org/rfc/rfc2822.txt
  32. *
  33. * ### Configuration
  34. *
  35. * Configuration for Email is managed by Email::config() and Email::configTransport().
  36. * Email::config() can be used to add or read a configuration profile for Email instances.
  37. * Once made configuration profiles can be used to re-use across various email messages your
  38. * application sends.
  39. *
  40. */
  41. class Email {
  42. use StaticConfigTrait;
  43. /**
  44. * Default X-Mailer
  45. *
  46. * @var string
  47. */
  48. const EMAIL_CLIENT = 'CakePHP Email';
  49. /**
  50. * Line length - no should more - RFC 2822 - 2.1.1
  51. *
  52. * @var int
  53. */
  54. const LINE_LENGTH_SHOULD = 78;
  55. /**
  56. * Line length - no must more - RFC 2822 - 2.1.1
  57. *
  58. * @var int
  59. */
  60. const LINE_LENGTH_MUST = 998;
  61. /**
  62. * Type of message - HTML
  63. *
  64. * @var string
  65. */
  66. const MESSAGE_HTML = 'html';
  67. /**
  68. * Type of message - TEXT
  69. *
  70. * @var string
  71. */
  72. const MESSAGE_TEXT = 'text';
  73. /**
  74. * Recipient of the email
  75. *
  76. * @var array
  77. */
  78. protected $_to = array();
  79. /**
  80. * The mail which the email is sent from
  81. *
  82. * @var array
  83. */
  84. protected $_from = array();
  85. /**
  86. * The sender email
  87. *
  88. * @var array
  89. */
  90. protected $_sender = array();
  91. /**
  92. * The email the recipient will reply to
  93. *
  94. * @var array
  95. */
  96. protected $_replyTo = array();
  97. /**
  98. * The read receipt email
  99. *
  100. * @var array
  101. */
  102. protected $_readReceipt = array();
  103. /**
  104. * The mail that will be used in case of any errors like
  105. * - Remote mailserver down
  106. * - Remote user has exceeded his quota
  107. * - Unknown user
  108. *
  109. * @var array
  110. */
  111. protected $_returnPath = array();
  112. /**
  113. * Carbon Copy
  114. *
  115. * List of email's that should receive a copy of the email.
  116. * The Recipient WILL be able to see this list
  117. *
  118. * @var array
  119. */
  120. protected $_cc = array();
  121. /**
  122. * Blind Carbon Copy
  123. *
  124. * List of email's that should receive a copy of the email.
  125. * The Recipient WILL NOT be able to see this list
  126. *
  127. * @var array
  128. */
  129. protected $_bcc = array();
  130. /**
  131. * Message ID
  132. *
  133. * @var bool|string
  134. */
  135. protected $_messageId = true;
  136. /**
  137. * Domain for messageId generation.
  138. * Needs to be manually set for CLI mailing as env('HTTP_HOST') is empty
  139. *
  140. * @var string
  141. */
  142. protected $_domain = null;
  143. /**
  144. * The subject of the email
  145. *
  146. * @var string
  147. */
  148. protected $_subject = '';
  149. /**
  150. * Associative array of a user defined headers
  151. * Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5
  152. *
  153. * @var array
  154. */
  155. protected $_headers = array();
  156. /**
  157. * Layout for the View
  158. *
  159. * @var string
  160. */
  161. protected $_layout = 'default';
  162. /**
  163. * Template for the view
  164. *
  165. * @var string
  166. */
  167. protected $_template = '';
  168. /**
  169. * View for render
  170. *
  171. * @var string
  172. */
  173. protected $_viewRender = 'Cake\View\View';
  174. /**
  175. * Vars to sent to render
  176. *
  177. * @var array
  178. */
  179. protected $_viewVars = array();
  180. /**
  181. * Theme for the View
  182. *
  183. * @var array
  184. */
  185. protected $_theme = null;
  186. /**
  187. * Helpers to be used in the render
  188. *
  189. * @var array
  190. */
  191. protected $_helpers = array('Html');
  192. /**
  193. * Text message
  194. *
  195. * @var string
  196. */
  197. protected $_textMessage = '';
  198. /**
  199. * Html message
  200. *
  201. * @var string
  202. */
  203. protected $_htmlMessage = '';
  204. /**
  205. * Final message to send
  206. *
  207. * @var array
  208. */
  209. protected $_message = array();
  210. /**
  211. * Available formats to be sent.
  212. *
  213. * @var array
  214. */
  215. protected $_emailFormatAvailable = array('text', 'html', 'both');
  216. /**
  217. * What format should the email be sent in
  218. *
  219. * @var string
  220. */
  221. protected $_emailFormat = 'text';
  222. /**
  223. * The transport instance to use for sending mail.
  224. *
  225. * @var string
  226. */
  227. protected $_transport = null;
  228. /**
  229. * Charset the email body is sent in
  230. *
  231. * @var string
  232. */
  233. public $charset = 'utf-8';
  234. /**
  235. * Charset the email header is sent in
  236. * If null, the $charset property will be used as default
  237. *
  238. * @var string
  239. */
  240. public $headerCharset = null;
  241. /**
  242. * The application wide charset, used to encode headers and body
  243. *
  244. * @var string
  245. */
  246. protected $_appCharset = null;
  247. /**
  248. * List of files that should be attached to the email.
  249. *
  250. * Only absolute paths
  251. *
  252. * @var array
  253. */
  254. protected $_attachments = array();
  255. /**
  256. * If set, boundary to use for multipart mime messages
  257. *
  258. * @var string
  259. */
  260. protected $_boundary = null;
  261. /**
  262. * Configuration profiles for transports.
  263. *
  264. * @var array
  265. */
  266. protected static $_transportConfig = [];
  267. /**
  268. * A copy of the configuration profile for this
  269. * instance. This copy can be modified with Email::profile().
  270. *
  271. * @var array
  272. */
  273. protected $_profile = [];
  274. /**
  275. * 8Bit character sets
  276. *
  277. * @var array
  278. */
  279. protected $_charset8bit = array('UTF-8', 'SHIFT_JIS');
  280. /**
  281. * Define Content-Type charset name
  282. *
  283. * @var array
  284. */
  285. protected $_contentTypeCharset = array(
  286. 'ISO-2022-JP-MS' => 'ISO-2022-JP'
  287. );
  288. /**
  289. * Regex for email validation
  290. *
  291. * If null, filter_var() will be used. Use the emailPattern() method
  292. * to set a custom pattern.'
  293. *
  294. * @var string
  295. */
  296. protected $_emailPattern = '/^((?:[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-.]+)$/ui';
  297. /**
  298. * The class name used for email configuration.
  299. *
  300. * @var string
  301. */
  302. protected $_configClass = 'EmailConfig';
  303. /**
  304. * Constructor
  305. *
  306. * @param array|string $config Array of configs, or string to load configs from email.php
  307. */
  308. public function __construct($config = null) {
  309. $this->_appCharset = Configure::read('App.encoding');
  310. if ($this->_appCharset !== null) {
  311. $this->charset = $this->_appCharset;
  312. }
  313. $this->_domain = preg_replace('/\:\d+$/', '', env('HTTP_HOST'));
  314. if (empty($this->_domain)) {
  315. $this->_domain = php_uname('n');
  316. }
  317. if ($config) {
  318. $this->profile($config);
  319. }
  320. if (empty($this->headerCharset)) {
  321. $this->headerCharset = $this->charset;
  322. }
  323. }
  324. /**
  325. * From
  326. *
  327. * @param string|array $email Null to get, String with email,
  328. * Array with email as key, name as value or email as value (without name)
  329. * @param string $name Name
  330. * @return array|$this
  331. * @throws \Cake\Network\Error\SocketException
  332. */
  333. public function from($email = null, $name = null) {
  334. if ($email === null) {
  335. return $this->_from;
  336. }
  337. return $this->_setEmailSingle('_from', $email, $name, 'From requires only 1 email address.');
  338. }
  339. /**
  340. * Sender
  341. *
  342. * @param string|array $email Null to get, String with email,
  343. * Array with email as key, name as value or email as value (without name)
  344. * @param string $name Name
  345. * @return array|$this
  346. * @throws \Cake\Network\Error\SocketException
  347. */
  348. public function sender($email = null, $name = null) {
  349. if ($email === null) {
  350. return $this->_sender;
  351. }
  352. return $this->_setEmailSingle('_sender', $email, $name, 'Sender requires only 1 email address.');
  353. }
  354. /**
  355. * Reply-To
  356. *
  357. * @param string|array $email Null to get, String with email,
  358. * Array with email as key, name as value or email as value (without name)
  359. * @param string $name Name
  360. * @return array|$this
  361. * @throws \Cake\Network\Error\SocketException
  362. */
  363. public function replyTo($email = null, $name = null) {
  364. if ($email === null) {
  365. return $this->_replyTo;
  366. }
  367. return $this->_setEmailSingle('_replyTo', $email, $name, 'Reply-To requires only 1 email address.');
  368. }
  369. /**
  370. * Read Receipt (Disposition-Notification-To header)
  371. *
  372. * @param string|array $email Null to get, String with email,
  373. * Array with email as key, name as value or email as value (without name)
  374. * @param string $name Name
  375. * @return array|$this
  376. * @throws \Cake\Network\Error\SocketException
  377. */
  378. public function readReceipt($email = null, $name = null) {
  379. if ($email === null) {
  380. return $this->_readReceipt;
  381. }
  382. return $this->_setEmailSingle('_readReceipt', $email, $name, 'Disposition-Notification-To requires only 1 email address.');
  383. }
  384. /**
  385. * Return Path
  386. *
  387. * @param string|array $email Null to get, String with email,
  388. * Array with email as key, name as value or email as value (without name)
  389. * @param string $name Name
  390. * @return array|$this
  391. * @throws \Cake\Network\Error\SocketException
  392. */
  393. public function returnPath($email = null, $name = null) {
  394. if ($email === null) {
  395. return $this->_returnPath;
  396. }
  397. return $this->_setEmailSingle('_returnPath', $email, $name, 'Return-Path requires only 1 email address.');
  398. }
  399. /**
  400. * To
  401. *
  402. * @param string|array $email Null to get, String with email,
  403. * Array with email as key, name as value or email as value (without name)
  404. * @param string $name Name
  405. * @return array|$this
  406. */
  407. public function to($email = null, $name = null) {
  408. if ($email === null) {
  409. return $this->_to;
  410. }
  411. return $this->_setEmail('_to', $email, $name);
  412. }
  413. /**
  414. * Add To
  415. *
  416. * @param string|array $email Null to get, String with email,
  417. * Array with email as key, name as value or email as value (without name)
  418. * @param string $name Name
  419. * @return $this
  420. */
  421. public function addTo($email, $name = null) {
  422. return $this->_addEmail('_to', $email, $name);
  423. }
  424. /**
  425. * Cc
  426. *
  427. * @param string|array $email Null to get, String with email,
  428. * Array with email as key, name as value or email as value (without name)
  429. * @param string $name Name
  430. * @return array|$this
  431. */
  432. public function cc($email = null, $name = null) {
  433. if ($email === null) {
  434. return $this->_cc;
  435. }
  436. return $this->_setEmail('_cc', $email, $name);
  437. }
  438. /**
  439. * Add Cc
  440. *
  441. * @param string|array $email Null to get, String with email,
  442. * Array with email as key, name as value or email as value (without name)
  443. * @param string $name Name
  444. * @return $this
  445. */
  446. public function addCc($email, $name = null) {
  447. return $this->_addEmail('_cc', $email, $name);
  448. }
  449. /**
  450. * Bcc
  451. *
  452. * @param string|array $email Null to get, String with email,
  453. * Array with email as key, name as value or email as value (without name)
  454. * @param string $name Name
  455. * @return array|$this
  456. */
  457. public function bcc($email = null, $name = null) {
  458. if ($email === null) {
  459. return $this->_bcc;
  460. }
  461. return $this->_setEmail('_bcc', $email, $name);
  462. }
  463. /**
  464. * Add Bcc
  465. *
  466. * @param string|array $email Null to get, String with email,
  467. * Array with email as key, name as value or email as value (without name)
  468. * @param string $name Name
  469. * @return $this
  470. */
  471. public function addBcc($email, $name = null) {
  472. return $this->_addEmail('_bcc', $email, $name);
  473. }
  474. /**
  475. * Charset setter/getter
  476. *
  477. * @param string $charset Character set.
  478. * @return string this->charset
  479. */
  480. public function charset($charset = null) {
  481. if ($charset === null) {
  482. return $this->charset;
  483. }
  484. $this->charset = $charset;
  485. if (empty($this->headerCharset)) {
  486. $this->headerCharset = $charset;
  487. }
  488. return $this->charset;
  489. }
  490. /**
  491. * HeaderCharset setter/getter
  492. *
  493. * @param string $charset Character set.
  494. * @return string this->charset
  495. */
  496. public function headerCharset($charset = null) {
  497. if ($charset === null) {
  498. return $this->headerCharset;
  499. }
  500. return $this->headerCharset = $charset;
  501. }
  502. /**
  503. * EmailPattern setter/getter
  504. *
  505. * @param string $regex for email address validation
  506. * @return string|$this
  507. */
  508. public function emailPattern($regex = false) {
  509. if ($regex === false) {
  510. return $this->_emailPattern;
  511. }
  512. $this->_emailPattern = $regex;
  513. return $this;
  514. }
  515. /**
  516. * Set email
  517. *
  518. * @param string $varName Property name
  519. * @param string|array $email String with email,
  520. * Array with email as key, name as value or email as value (without name)
  521. * @param string $name Name
  522. * @return $this
  523. * @throws \Cake\Network\Error\SocketException
  524. */
  525. protected function _setEmail($varName, $email, $name) {
  526. if (!is_array($email)) {
  527. $this->_validateEmail($email);
  528. if ($name === null) {
  529. $name = $email;
  530. }
  531. $this->{$varName} = array($email => $name);
  532. return $this;
  533. }
  534. $list = array();
  535. foreach ($email as $key => $value) {
  536. if (is_int($key)) {
  537. $key = $value;
  538. }
  539. $this->_validateEmail($key);
  540. $list[$key] = $value;
  541. }
  542. $this->{$varName} = $list;
  543. return $this;
  544. }
  545. /**
  546. * Validate email address
  547. *
  548. * @param string $email Email address to validate
  549. * @return void
  550. * @throws \Cake\Network\Error\SocketException If email address does not validate
  551. */
  552. protected function _validateEmail($email) {
  553. if ($this->_emailPattern === null && filter_var($email, FILTER_VALIDATE_EMAIL)) {
  554. return;
  555. } elseif (preg_match($this->_emailPattern, $email)) {
  556. return;
  557. }
  558. throw new Error\SocketException(__d('cake_dev', 'Invalid email: "%s"', $email));
  559. }
  560. /**
  561. * Set only 1 email
  562. *
  563. * @param string $varName Property name
  564. * @param string|array $email String with email,
  565. * Array with email as key, name as value or email as value (without name)
  566. * @param string $name Name
  567. * @param string $throwMessage Exception message
  568. * @return $this
  569. * @throws \Cake\Network\Error\SocketException
  570. */
  571. protected function _setEmailSingle($varName, $email, $name, $throwMessage) {
  572. $current = $this->{$varName};
  573. $this->_setEmail($varName, $email, $name);
  574. if (count($this->{$varName}) !== 1) {
  575. $this->{$varName} = $current;
  576. throw new Error\SocketException($throwMessage);
  577. }
  578. return $this;
  579. }
  580. /**
  581. * Add email
  582. *
  583. * @param string $varName Property name
  584. * @param string|array $email String with email,
  585. * Array with email as key, name as value or email as value (without name)
  586. * @param string $name Name
  587. * @return $this
  588. * @throws \Cake\Network\Error\SocketException
  589. */
  590. protected function _addEmail($varName, $email, $name) {
  591. if (!is_array($email)) {
  592. $this->_validateEmail($email);
  593. if ($name === null) {
  594. $name = $email;
  595. }
  596. $this->{$varName}[$email] = $name;
  597. return $this;
  598. }
  599. $list = array();
  600. foreach ($email as $key => $value) {
  601. if (is_int($key)) {
  602. $key = $value;
  603. }
  604. $this->_validateEmail($key);
  605. $list[$key] = $value;
  606. }
  607. $this->{$varName} = array_merge($this->{$varName}, $list);
  608. return $this;
  609. }
  610. /**
  611. * Get/Set Subject.
  612. *
  613. * @param string $subject Subject string.
  614. * @return string|$this
  615. */
  616. public function subject($subject = null) {
  617. if ($subject === null) {
  618. return $this->_subject;
  619. }
  620. $this->_subject = $this->_encode((string)$subject);
  621. return $this;
  622. }
  623. /**
  624. * Sets headers for the message
  625. *
  626. * @param array $headers Associative array containing headers to be set.
  627. * @return $this
  628. * @throws \Cake\Network\Error\SocketException
  629. */
  630. public function setHeaders($headers) {
  631. if (!is_array($headers)) {
  632. throw new Error\SocketException('$headers should be an array.');
  633. }
  634. $this->_headers = $headers;
  635. return $this;
  636. }
  637. /**
  638. * Add header for the message
  639. *
  640. * @param array $headers Headers to set.
  641. * @return $this
  642. * @throws \Cake\Network\Error\SocketException
  643. */
  644. public function addHeaders($headers) {
  645. if (!is_array($headers)) {
  646. throw new Error\SocketException('$headers should be an array.');
  647. }
  648. $this->_headers = array_merge($this->_headers, $headers);
  649. return $this;
  650. }
  651. /**
  652. * Get list of headers
  653. *
  654. * ### Includes:
  655. *
  656. * - `from`
  657. * - `replyTo`
  658. * - `readReceipt`
  659. * - `returnPath`
  660. * - `to`
  661. * - `cc`
  662. * - `bcc`
  663. * - `subject`
  664. *
  665. * @param array $include List of headers.
  666. * @return array
  667. */
  668. public function getHeaders(array $include = array()) {
  669. if ($include == array_values($include)) {
  670. $include = array_fill_keys($include, true);
  671. }
  672. $defaults = array_fill_keys(
  673. array(
  674. 'from', 'sender', 'replyTo', 'readReceipt', 'returnPath',
  675. 'to', 'cc', 'bcc', 'subject'),
  676. false
  677. );
  678. $include += $defaults;
  679. $headers = array();
  680. $relation = array(
  681. 'from' => 'From',
  682. 'replyTo' => 'Reply-To',
  683. 'readReceipt' => 'Disposition-Notification-To',
  684. 'returnPath' => 'Return-Path'
  685. );
  686. foreach ($relation as $var => $header) {
  687. if ($include[$var]) {
  688. $var = '_' . $var;
  689. $headers[$header] = current($this->_formatAddress($this->{$var}));
  690. }
  691. }
  692. if ($include['sender']) {
  693. if (key($this->_sender) === key($this->_from)) {
  694. $headers['Sender'] = '';
  695. } else {
  696. $headers['Sender'] = current($this->_formatAddress($this->_sender));
  697. }
  698. }
  699. foreach (array('to', 'cc', 'bcc') as $var) {
  700. if ($include[$var]) {
  701. $classVar = '_' . $var;
  702. $headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar}));
  703. }
  704. }
  705. $headers += $this->_headers;
  706. if (!isset($headers['X-Mailer'])) {
  707. $headers['X-Mailer'] = static::EMAIL_CLIENT;
  708. }
  709. if (!isset($headers['Date'])) {
  710. $headers['Date'] = date(DATE_RFC2822);
  711. }
  712. if ($this->_messageId !== false) {
  713. if ($this->_messageId === true) {
  714. $headers['Message-ID'] = '<' . str_replace('-', '', String::UUID()) . '@' . $this->_domain . '>';
  715. } else {
  716. $headers['Message-ID'] = $this->_messageId;
  717. }
  718. }
  719. if ($include['subject']) {
  720. $headers['Subject'] = $this->_subject;
  721. }
  722. $headers['MIME-Version'] = '1.0';
  723. if (!empty($this->_attachments)) {
  724. $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"';
  725. } elseif ($this->_emailFormat === 'both') {
  726. $headers['Content-Type'] = 'multipart/alternative; boundary="' . $this->_boundary . '"';
  727. } elseif ($this->_emailFormat === 'text') {
  728. $headers['Content-Type'] = 'text/plain; charset=' . $this->_getContentTypeCharset();
  729. } elseif ($this->_emailFormat === 'html') {
  730. $headers['Content-Type'] = 'text/html; charset=' . $this->_getContentTypeCharset();
  731. }
  732. $headers['Content-Transfer-Encoding'] = $this->_getContentTransferEncoding();
  733. return $headers;
  734. }
  735. /**
  736. * Format addresses
  737. *
  738. * If the address contains non alphanumeric/whitespace characters, it will
  739. * be quoted as characters like `:` and `,` are known to cause issues
  740. * in address header fields.
  741. *
  742. * @param array $address Addresses to format.
  743. * @return array
  744. */
  745. protected function _formatAddress($address) {
  746. $return = array();
  747. foreach ($address as $email => $alias) {
  748. if ($email === $alias) {
  749. $return[] = $email;
  750. } else {
  751. $encoded = $this->_encode($alias);
  752. if ($encoded === $alias && preg_match('/[^a-z0-9 ]/i', $encoded)) {
  753. $encoded = '"' . str_replace('"', '\"', $encoded) . '"';
  754. }
  755. $return[] = sprintf('%s <%s>', $encoded, $email);
  756. }
  757. }
  758. return $return;
  759. }
  760. /**
  761. * Template and layout
  762. *
  763. * @param bool|string $template Template name or null to not use
  764. * @param bool|string $layout Layout name or null to not use
  765. * @return array|$this
  766. */
  767. public function template($template = false, $layout = false) {
  768. if ($template === false) {
  769. return array(
  770. 'template' => $this->_template,
  771. 'layout' => $this->_layout
  772. );
  773. }
  774. $this->_template = $template;
  775. if ($layout !== false) {
  776. $this->_layout = $layout;
  777. }
  778. return $this;
  779. }
  780. /**
  781. * View class for render
  782. *
  783. * @param string $viewClass View class name.
  784. * @return string|$this
  785. */
  786. public function viewRender($viewClass = null) {
  787. if ($viewClass === null) {
  788. return $this->_viewRender;
  789. }
  790. $this->_viewRender = $viewClass;
  791. return $this;
  792. }
  793. /**
  794. * Variables to be set on render
  795. *
  796. * @param array $viewVars Variables to set for view.
  797. * @return array|$this
  798. */
  799. public function viewVars($viewVars = null) {
  800. if ($viewVars === null) {
  801. return $this->_viewVars;
  802. }
  803. $this->_viewVars = array_merge($this->_viewVars, (array)$viewVars);
  804. return $this;
  805. }
  806. /**
  807. * Theme to use when rendering
  808. *
  809. * @param string $theme Theme name.
  810. * @return string|$this
  811. */
  812. public function theme($theme = null) {
  813. if ($theme === null) {
  814. return $this->_theme;
  815. }
  816. $this->_theme = $theme;
  817. return $this;
  818. }
  819. /**
  820. * Helpers to be used in render
  821. *
  822. * @param array $helpers Helpers list.
  823. * @return array|$this
  824. */
  825. public function helpers($helpers = null) {
  826. if ($helpers === null) {
  827. return $this->_helpers;
  828. }
  829. $this->_helpers = (array)$helpers;
  830. return $this;
  831. }
  832. /**
  833. * Email format
  834. *
  835. * @param string $format Formatting string.
  836. * @return string|$this
  837. * @throws \Cake\Network\Error\SocketException
  838. */
  839. public function emailFormat($format = null) {
  840. if ($format === null) {
  841. return $this->_emailFormat;
  842. }
  843. if (!in_array($format, $this->_emailFormatAvailable)) {
  844. throw new Error\SocketException('Format not available.');
  845. }
  846. $this->_emailFormat = $format;
  847. return $this;
  848. }
  849. /**
  850. * Get/set the transport.
  851. *
  852. * When setting the transport you can either use the name
  853. * of a configured transport or supply a constructed transport.
  854. *
  855. * @param string|AbstractTransport $name Either the name of a configured
  856. * transport, or a transport instance.
  857. * @return \Cake\Network\Email\AbstractTransport|$this
  858. * @throws \Cake\Network\Error\SocketException When the chosen transport lacks a send method.
  859. */
  860. public function transport($name = null) {
  861. if ($name === null) {
  862. return $this->_transport;
  863. }
  864. if (is_string($name)) {
  865. $transport = $this->_constructTransport($name);
  866. } elseif (is_object($name)) {
  867. $transport = $name;
  868. }
  869. if (!method_exists($transport, 'send')) {
  870. throw new Error\SocketException(sprintf('The "%s" do not have send method.', get_class($transport)));
  871. }
  872. $this->_transport = $transport;
  873. return $this;
  874. }
  875. /**
  876. * Build a transport instance from configuration data.
  877. *
  878. * @param string $name The transport configuration name to build.
  879. * @return \Cake\Network\Email\AbstractTransport
  880. * @throws \Cake\Error\Exception When transport configuration is missing or invalid.
  881. */
  882. protected function _constructTransport($name) {
  883. if (!isset(static::$_transportConfig[$name]['className'])) {
  884. throw new Exception(sprintf('Transport config "%s" is missing.', $name));
  885. }
  886. $config = static::$_transportConfig[$name];
  887. if (is_object($config['className'])) {
  888. return $config['className'];
  889. }
  890. $className = App::className($config['className'], 'Network/Email', 'Transport');
  891. if (!$className) {
  892. throw new Exception(sprintf('Transport class "%s" not found.', $name));
  893. } elseif (!method_exists($className, 'send')) {
  894. throw new Exception(sprintf('The "%s" does not have a send() method.', $className));
  895. }
  896. unset($config['className']);
  897. return new $className($config);
  898. }
  899. /**
  900. * Message-ID
  901. *
  902. * @param bool|string $message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID
  903. * @return bool|string|$this
  904. * @throws \Cake\Network\Error\SocketException
  905. */
  906. public function messageId($message = null) {
  907. if ($message === null) {
  908. return $this->_messageId;
  909. }
  910. if (is_bool($message)) {
  911. $this->_messageId = $message;
  912. } else {
  913. if (!preg_match('/^\<.+@.+\>$/', $message)) {
  914. throw new Error\SocketException('Invalid format to Message-ID. The text should be something like "<uuid@server.com>"');
  915. }
  916. $this->_messageId = $message;
  917. }
  918. return $this;
  919. }
  920. /**
  921. * Domain as top level (the part after @)
  922. *
  923. * @param string $domain Manually set the domain for CLI mailing
  924. * @return string|$this
  925. */
  926. public function domain($domain = null) {
  927. if ($domain === null) {
  928. return $this->_domain;
  929. }
  930. $this->_domain = $domain;
  931. return $this;
  932. }
  933. /**
  934. * Add attachments to the email message
  935. *
  936. * Attachments can be defined in a few forms depending on how much control you need:
  937. *
  938. * Attach a single file:
  939. *
  940. * {{{
  941. * $email->attachments('path/to/file');
  942. * }}}
  943. *
  944. * Attach a file with a different filename:
  945. *
  946. * {{{
  947. * $email->attachments(array('custom_name.txt' => 'path/to/file.txt'));
  948. * }}}
  949. *
  950. * Attach a file and specify additional properties:
  951. *
  952. * {{{
  953. * $email->attachments(array('custom_name.png' => array(
  954. * 'file' => 'path/to/file',
  955. * 'mimetype' => 'image/png',
  956. * 'contentId' => 'abc123',
  957. * 'contentDisposition' => false
  958. * ));
  959. * }}}
  960. *
  961. * Attach a file from string and specify additional properties:
  962. *
  963. * {{{
  964. * $email->attachments(array('custom_name.png' => array(
  965. * 'data' => file_get_contents('path/to/file'),
  966. * 'mimetype' => 'image/png'
  967. * ));
  968. * }}}
  969. *
  970. * The `contentId` key allows you to specify an inline attachment. In your email text, you
  971. * can use `<img src="cid:abc123" />` to display the image inline.
  972. *
  973. * The `contentDisposition` key allows you to disable the `Content-Disposition` header, this can improve
  974. * attachment compatibility with outlook email clients.
  975. *
  976. * @param string|array $attachments String with the filename or array with filenames
  977. * @return array|$this Either the array of attachments when getting or $this when setting.
  978. * @throws \Cake\Network\Error\SocketException
  979. */
  980. public function attachments($attachments = null) {
  981. if ($attachments === null) {
  982. return $this->_attachments;
  983. }
  984. $attach = array();
  985. foreach ((array)$attachments as $name => $fileInfo) {
  986. if (!is_array($fileInfo)) {
  987. $fileInfo = array('file' => $fileInfo);
  988. }
  989. if (!isset($fileInfo['file'])) {
  990. if (!isset($fileInfo['data'])) {
  991. throw new Error\SocketException('No file or data specified.');
  992. }
  993. if (is_int($name)) {
  994. throw new Error\SocketException('No filename specified.');
  995. }
  996. $fileInfo['data'] = chunk_split(base64_encode($fileInfo['data']), 76, "\r\n");
  997. } else {
  998. $fileName = $fileInfo['file'];
  999. $fileInfo['file'] = realpath($fileInfo['file']);
  1000. if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) {
  1001. throw new Error\SocketException(sprintf('File not found: "%s"', $fileName));
  1002. }
  1003. if (is_int($name)) {
  1004. $name = basename($fileInfo['file']);
  1005. }
  1006. }
  1007. if (!isset($fileInfo['mimetype'])) {
  1008. $fileInfo['mimetype'] = 'application/octet-stream';
  1009. }
  1010. $attach[$name] = $fileInfo;
  1011. }
  1012. $this->_attachments = $attach;
  1013. return $this;
  1014. }
  1015. /**
  1016. * Add attachments
  1017. *
  1018. * @param string|array $attachments String with the filename or array with filenames
  1019. * @return $this
  1020. * @throws \Cake\Network\Error\SocketException
  1021. * @see \Cake\Network\Email\Email::attachments()
  1022. */
  1023. public function addAttachments($attachments) {
  1024. $current = $this->_attachments;
  1025. $this->attachments($attachments);
  1026. $this->_attachments = array_merge($current, $this->_attachments);
  1027. return $this;
  1028. }
  1029. /**
  1030. * Get generated message (used by transport classes)
  1031. *
  1032. * @param string $type Use MESSAGE_* constants or null to return the full message as array
  1033. * @return string|array String if have type, array if type is null
  1034. */
  1035. public function message($type = null) {
  1036. switch ($type) {
  1037. case static::MESSAGE_HTML:
  1038. return $this->_htmlMessage;
  1039. case static::MESSAGE_TEXT:
  1040. return $this->_textMessage;
  1041. }
  1042. return $this->_message;
  1043. }
  1044. /**
  1045. * Add or read transport configuration.
  1046. *
  1047. * Use this method to define transports to use in delivery profiles.
  1048. * Once defined you cannot edit the configurations, and must use
  1049. * Email::dropTransport() to flush the configuration first.
  1050. *
  1051. * When using an array of configuration data a new transport
  1052. * will be constructed for each message sent. When using a Closure, the
  1053. * closure will be evaluated for each message.
  1054. *
  1055. * The `className` is used to define the class to use for a transport.
  1056. * It can either be a short name, or a fully qualified classname
  1057. *
  1058. * @param string|array $key The configuration name to read/write. Or
  1059. * an array of multiple transports to set.
  1060. * @param array|AbstractTransport $config Either an array of configuration
  1061. * data, or a transport instance.
  1062. * @return mixed Either null when setting or an array of data when reading.
  1063. * @throws \Cake\Error\Exception When modifying an existing configuration.
  1064. */
  1065. public static function configTransport($key, $config = null) {
  1066. if ($config === null && is_string($key)) {
  1067. return isset(static::$_transportConfig[$key]) ? static::$_transportConfig[$key] : null;
  1068. }
  1069. if ($config === null && is_array($key)) {
  1070. foreach ($key as $name => $settings) {
  1071. static::configTransport($name, $settings);
  1072. }
  1073. return;
  1074. }
  1075. if (isset(static::$_transportConfig[$key])) {
  1076. throw new Exception(sprintf('Cannot modify an existing config "%s"', $key));
  1077. }
  1078. if (is_object($config)) {
  1079. $config = ['className' => $config];
  1080. }
  1081. static::$_transportConfig[$key] = $config;
  1082. }
  1083. /**
  1084. * Delete transport configuration.
  1085. *
  1086. * @param string $key The transport name to remove.
  1087. * @return void
  1088. */
  1089. public static function dropTransport($key) {
  1090. unset(static::$_transportConfig[$key]);
  1091. }
  1092. /**
  1093. * Get/Set the configuration profile to use for this instance.
  1094. *
  1095. * @param null|string|array $config String with configuration name, or
  1096. * an array with config or null to return current config.
  1097. * @return string|array|$this
  1098. */
  1099. public function profile($config = null) {
  1100. if ($config === null) {
  1101. return $this->_profile;
  1102. }
  1103. if (!is_array($config)) {
  1104. $config = (string)$config;
  1105. }
  1106. $this->_applyConfig($config);
  1107. return $this;
  1108. }
  1109. /**
  1110. * Send an email using the specified content, template and layout
  1111. *
  1112. * @param string|array $content String with message or array with messages
  1113. * @return array
  1114. * @throws \Cake\Network\Error\SocketException
  1115. */
  1116. public function send($content = null) {
  1117. if (empty($this->_from)) {
  1118. throw new Error\SocketException('From is not specified.');
  1119. }
  1120. if (empty($this->_to) && empty($this->_cc) && empty($this->_bcc)) {
  1121. throw new Error\SocketException('You need specify one destination on to, cc or bcc.');
  1122. }
  1123. if (is_array($content)) {
  1124. $content = implode("\n", $content) . "\n";
  1125. }
  1126. $this->_message = $this->_render($this->_wrap($content));
  1127. $contents = $this->transport()->send($this);
  1128. if (!empty($this->_profile['log'])) {
  1129. $config = [
  1130. 'level' => LOG_DEBUG,
  1131. 'scope' => 'email'
  1132. ];
  1133. if ($this->_profile['log'] !== true) {
  1134. if (!is_array($this->_profile['log'])) {
  1135. $this->_profile['log'] = ['level' => $this->_profile['log']];
  1136. }
  1137. $config = $this->_profile['log'] + $config;
  1138. }
  1139. Log::write(
  1140. $config['level'],
  1141. PHP_EOL . $contents['headers'] . PHP_EOL . $contents['message'],
  1142. $config['scope']
  1143. );
  1144. }
  1145. return $contents;
  1146. }
  1147. /**
  1148. * Static method to fast create an instance of \Cake\Network\Email\Email
  1149. *
  1150. * @param string|array $to Address to send (see Cake\Network\Email\Email::to()). If null, will try to use 'to' from transport config
  1151. * @param string $subject String of subject or null to use 'subject' from transport config
  1152. * @param string|array $message String with message or array with variables to be used in render
  1153. * @param string|array $transportConfig String to use config from EmailConfig or array with configs
  1154. * @param bool $send Send the email or just return the instance pre-configured
  1155. * @return \Cake\Network\Email\Email Instance of Cake\Network\Email\Email
  1156. * @throws \Cake\Network\Error\SocketException
  1157. */
  1158. public static function deliver($to = null, $subject = null, $message = null, $transportConfig = 'fast', $send = true) {
  1159. $class = __CLASS__;
  1160. $instance = new $class($transportConfig);
  1161. if ($to !== null) {
  1162. $instance->to($to);
  1163. }
  1164. if ($subject !== null) {
  1165. $instance->subject($subject);
  1166. }
  1167. if (is_array($message)) {
  1168. $instance->viewVars($message);
  1169. $message = null;
  1170. } elseif ($message === null && array_key_exists('message', $config = $instance->profile())) {
  1171. $message = $config['message'];
  1172. }
  1173. if ($send === true) {
  1174. $instance->send($message);
  1175. }
  1176. return $instance;
  1177. }
  1178. /**
  1179. * Apply the config to an instance
  1180. *
  1181. * @param string|array $config Configuration options.
  1182. * @return void
  1183. * @throws \Cake\Error\Exception When using a configuration that doesn't exist.
  1184. */
  1185. protected function _applyConfig($config) {
  1186. if (is_string($config)) {
  1187. $name = $config;
  1188. $config = static::config($name);
  1189. if (empty($config)) {
  1190. throw new Exception(sprintf('Unknown email configuration "%s".', $name));
  1191. }
  1192. unset($name);
  1193. }
  1194. $this->_profile = array_merge($this->_profile, $config);
  1195. if (!empty($config['charset'])) {
  1196. $this->charset = $config['charset'];
  1197. }
  1198. if (!empty($config['headerCharset'])) {
  1199. $this->headerCharset = $config['headerCharset'];
  1200. }
  1201. if (empty($this->headerCharset)) {
  1202. $this->headerCharset = $this->charset;
  1203. }
  1204. $simpleMethods = array(
  1205. 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', 'cc', 'bcc',
  1206. 'messageId', 'domain', 'subject', 'viewRender', 'viewVars', 'attachments',
  1207. 'transport', 'emailFormat', 'theme', 'helpers', 'emailPattern'
  1208. );
  1209. foreach ($simpleMethods as $method) {
  1210. if (isset($config[$method])) {
  1211. $this->$method($config[$method]);
  1212. unset($config[$method]);
  1213. }
  1214. }
  1215. if (isset($config['headers'])) {
  1216. $this->setHeaders($config['headers']);
  1217. unset($config['headers']);
  1218. }
  1219. if (array_key_exists('template', $config)) {
  1220. $this->_template = $config['template'];
  1221. }
  1222. if (array_key_exists('layout', $config)) {
  1223. $this->_layout = $config['layout'];
  1224. }
  1225. }
  1226. /**
  1227. * Reset all the internal variables to be able to send out a new email.
  1228. *
  1229. * @return $this
  1230. */
  1231. public function reset() {
  1232. $this->_to = array();
  1233. $this->_from = array();
  1234. $this->_sender = array();
  1235. $this->_replyTo = array();
  1236. $this->_readReceipt = array();
  1237. $this->_returnPath = array();
  1238. $this->_cc = array();
  1239. $this->_bcc = array();
  1240. $this->_messageId = true;
  1241. $this->_subject = '';
  1242. $this->_headers = array();
  1243. $this->_layout = 'default';
  1244. $this->_template = '';
  1245. $this->_viewRender = 'Cake\View\View';
  1246. $this->_viewVars = array();
  1247. $this->_theme = null;
  1248. $this->_helpers = array('Html');
  1249. $this->_textMessage = '';
  1250. $this->_htmlMessage = '';
  1251. $this->_message = '';
  1252. $this->_emailFormat = 'text';
  1253. $this->_transport = 'default';
  1254. $this->charset = 'utf-8';
  1255. $this->headerCharset = null;
  1256. $this->_attachments = array();
  1257. $this->_profile = array();
  1258. $this->_emailPattern = null;
  1259. return $this;
  1260. }
  1261. /**
  1262. * Encode the specified string using the current charset
  1263. *
  1264. * @param string $text String to encode
  1265. * @return string Encoded string
  1266. */
  1267. protected function _encode($text) {
  1268. $restore = mb_internal_encoding();
  1269. mb_internal_encoding($this->_appCharset);
  1270. if (empty($this->headerCharset)) {
  1271. $this->headerCharset = $this->charset;
  1272. }
  1273. $return = mb_encode_mimeheader($text, $this->headerCharset, 'B');
  1274. mb_internal_encoding($restore);
  1275. return $return;
  1276. }
  1277. /**
  1278. * Translates a string for one charset to another if the App.encoding value
  1279. * differs and the mb_convert_encoding function exists
  1280. *
  1281. * @param string $text The text to be converted
  1282. * @param string $charset the target encoding
  1283. * @return string
  1284. */
  1285. protected function _encodeString($text, $charset) {
  1286. if ($this->_appCharset === $charset) {
  1287. return $text;
  1288. }
  1289. return mb_convert_encoding($text, $charset, $this->_appCharset);
  1290. }
  1291. /**
  1292. * Wrap the message to follow the RFC 2822 - 2.1.1
  1293. *
  1294. * @param string $message Message to wrap
  1295. * @param int $wrapLength The line length
  1296. * @return array Wrapped message
  1297. */
  1298. protected function _wrap($message, $wrapLength = Email::LINE_LENGTH_MUST) {
  1299. if (strlen($message) === 0) {
  1300. return array('');
  1301. }
  1302. $message = str_replace(array("\r\n", "\r"), "\n", $message);
  1303. $lines = explode("\n", $message);
  1304. $formatted = array();
  1305. $cut = ($wrapLength == Email::LINE_LENGTH_MUST);
  1306. foreach ($lines as $line) {
  1307. if (empty($line)) {
  1308. $formatted[] = '';
  1309. continue;
  1310. }
  1311. if (strlen($line) < $wrapLength) {
  1312. $formatted[] = $line;
  1313. continue;
  1314. }
  1315. if (!preg_match('/<[a-z]+.*>/i', $line)) {
  1316. $formatted = array_merge(
  1317. $formatted,
  1318. explode("\n", wordwrap($line, $wrapLength, "\n", $cut))
  1319. );
  1320. continue;
  1321. }
  1322. $tagOpen = false;
  1323. $tmpLine = $tag = '';
  1324. $tmpLineLength = 0;
  1325. for ($i = 0, $count = strlen($line); $i < $count; $i++) {
  1326. $char = $line[$i];
  1327. if ($tagOpen) {
  1328. $tag .= $char;
  1329. if ($char === '>') {
  1330. $tagLength = strlen($tag);
  1331. if ($tagLength + $tmpLineLength < $wrapLength) {
  1332. $tmpLine .= $tag;
  1333. $tmpLineLength += $tagLength;
  1334. } else {
  1335. if ($tmpLineLength > 0) {
  1336. $formatted = array_merge(
  1337. $formatted,
  1338. explode("\n", wordwrap(trim($tmpLine), $wrapLength, "\n", $cut))
  1339. );
  1340. $tmpLine = '';
  1341. $tmpLineLength = 0;
  1342. }
  1343. if ($tagLength > $wrapLength) {
  1344. $formatted[] = $tag;
  1345. } else {
  1346. $tmpLine = $tag;
  1347. $tmpLineLength = $tagLength;
  1348. }
  1349. }
  1350. $tag = '';
  1351. $tagOpen = false;
  1352. }
  1353. continue;
  1354. }
  1355. if ($char === '<') {
  1356. $tagOpen = true;
  1357. $tag = '<';
  1358. continue;
  1359. }
  1360. if ($char === ' ' && $tmpLineLength >= $wrapLength) {
  1361. $formatted[] = $tmpLine;
  1362. $tmpLineLength = 0;
  1363. continue;
  1364. }
  1365. $tmpLine .= $char;
  1366. $tmpLineLength++;
  1367. if ($tmpLineLength === $wrapLength) {
  1368. $nextChar = $line[$i + 1];
  1369. if ($nextChar === ' ' || $nextChar === '<') {
  1370. $formatted[] = trim($tmpLine);
  1371. $tmpLine = '';
  1372. $tmpLineLength = 0;
  1373. if ($nextChar === ' ') {
  1374. $i++;
  1375. }
  1376. } else {
  1377. $lastSpace = strrpos($tmpLine, ' ');
  1378. if ($lastSpace === false) {
  1379. continue;
  1380. }
  1381. $formatted[] = trim(substr($tmpLine, 0, $lastSpace));
  1382. $tmpLine = substr($tmpLine, $lastSpace + 1);
  1383. $tmpLineLength = strlen($tmpLine);
  1384. }
  1385. }
  1386. }
  1387. if (!empty($tmpLine)) {
  1388. $formatted[] = $tmpLine;
  1389. }
  1390. }
  1391. $formatted[] = '';
  1392. return $formatted;
  1393. }
  1394. /**
  1395. * Create unique boundary identifier
  1396. *
  1397. * @return void
  1398. */
  1399. protected function _createBoundary() {
  1400. if (!empty($this->_attachments) || $this->_emailFormat === 'both') {
  1401. $this->_boundary = md5(uniqid(time()));
  1402. }
  1403. }
  1404. /**
  1405. * Attach non-embedded files by adding file contents inside boundaries.
  1406. *
  1407. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  1408. * @return array An array of lines to add to the message
  1409. */
  1410. protected function _attachFiles($boundary = null) {
  1411. if ($boundary === null) {
  1412. $boundary = $this->_boundary;
  1413. }
  1414. $msg = array();
  1415. foreach ($this->_attachments as $filename => $fileInfo) {
  1416. if (!empty($fileInfo['contentId'])) {
  1417. continue;
  1418. }
  1419. $data = isset($fileInfo['data']) ? $fileInfo['data'] : $this->_readFile($fileInfo['file']);
  1420. $hasDisposition = (
  1421. !isset($fileInfo['contentDisposition']) ||
  1422. $fileInfo['contentDisposition']
  1423. );
  1424. $part = new Part(false, $data, false);
  1425. if ($hasDisposition) {
  1426. $part->disposition('attachment');
  1427. $part->filename($filename);
  1428. }
  1429. $part->transferEncoding('base64');
  1430. $part->type($fileInfo['mimetype']);
  1431. $msg[] = '--' . $boundary;
  1432. $msg[] = (string)$part;
  1433. $msg[] = '';
  1434. }
  1435. return $msg;
  1436. }
  1437. /**
  1438. * Read the file contents and return a base64 version of the file contents.
  1439. *
  1440. * @param string $path The absolute path to the file to read.
  1441. * @return string File contents in base64 encoding
  1442. */
  1443. protected function _readFile($path) {
  1444. $File = new File($path);
  1445. return chunk_split(base64_encode($File->read()));
  1446. }
  1447. /**
  1448. * Attach inline/embedded files to the message.
  1449. *
  1450. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  1451. * @return array An array of lines to add to the message
  1452. */
  1453. protected function _attachInlineFiles($boundary = null) {
  1454. if ($boundary === null) {
  1455. $boundary = $this->_boundary;
  1456. }
  1457. $msg = array();
  1458. foreach ($this->_attachments as $filename => $fileInfo) {
  1459. if (empty($fileInfo['contentId'])) {
  1460. continue;
  1461. }
  1462. $data = isset($fileInfo['data']) ? $fileInfo['data'] : $this->_readFile($fileInfo['file']);
  1463. $msg[] = '--' . $boundary;
  1464. $part = new Part(false, $data, 'inline');
  1465. $part->type($fileInfo['mimetype']);
  1466. $part->transferEncoding('base64');
  1467. $part->contentId($fileInfo['contentId']);
  1468. $part->filename($filename);
  1469. $msg[] = (string)$part;
  1470. $msg[] = '';
  1471. }
  1472. return $msg;
  1473. }
  1474. /**
  1475. * Render the body of the email.
  1476. *
  1477. * @param array $content Content to render
  1478. * @return array Email body ready to be sent
  1479. */
  1480. protected function _render($content) {
  1481. $this->_textMessage = $this->_htmlMessage = '';
  1482. $content = implode("\n", $content);
  1483. $rendered = $this->_renderTemplates($content);
  1484. $this->_createBoundary();
  1485. $msg = array();
  1486. $contentIds = array_filter((array)Hash::extract($this->_attachments, '{s}.contentId'));
  1487. $hasInlineAttachments = count($contentIds) > 0;
  1488. $hasAttachments = !empty($this->_attachments);
  1489. $hasMultipleTypes = count($rendered) > 1;
  1490. $multiPart = ($hasAttachments || $hasMultipleTypes);
  1491. $boundary = $relBoundary = $textBoundary = $this->_boundary;
  1492. if ($hasInlineAttachments) {
  1493. $msg[] = '--' . $boundary;
  1494. $msg[] = 'Content-Type: multipart/related; boundary="rel-' . $boundary . '"';
  1495. $msg[] = '';
  1496. $relBoundary = $textBoundary = 'rel-' . $boundary;
  1497. }
  1498. if ($hasMultipleTypes && $hasAttachments) {
  1499. $msg[] = '--' . $relBoundary;
  1500. $msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $boundary . '"';
  1501. $msg[] = '';
  1502. $textBoundary = 'alt-' . $boundary;
  1503. }
  1504. if (isset($rendered['text'])) {
  1505. if ($multiPart) {
  1506. $msg[] = '--' . $textBoundary;
  1507. $msg[] = 'Content-Type: text/plain; charset=' . $this->_getContentTypeCharset();
  1508. $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding();
  1509. $msg[] = '';
  1510. }
  1511. $this->_textMessage = $rendered['text'];
  1512. $content = explode("\n", $this->_textMessage);
  1513. $msg = array_merge($msg, $content);
  1514. $msg[] = '';
  1515. }
  1516. if (isset($rendered['html'])) {
  1517. if ($multiPart) {
  1518. $msg[] = '--' . $textBoundary;
  1519. $msg[] = 'Content-Type: text/html; charset=' . $this->_getContentTypeCharset();
  1520. $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding();
  1521. $msg[] = '';
  1522. }
  1523. $this->_htmlMessage = $rendered['html'];
  1524. $content = explode("\n", $this->_htmlMessage);
  1525. $msg = array_merge($msg, $content);
  1526. $msg[] = '';
  1527. }
  1528. if ($textBoundary !== $relBoundary) {
  1529. $msg[] = '--' . $textBoundary . '--';
  1530. $msg[] = '';
  1531. }
  1532. if ($hasInlineAttachments) {
  1533. $attachments = $this->_attachInlineFiles($relBoundary);
  1534. $msg = array_merge($msg, $attachments);
  1535. $msg[] = '';
  1536. $msg[] = '--' . $relBoundary . '--';
  1537. $msg[] = '';
  1538. }
  1539. if ($hasAttachments) {
  1540. $attachments = $this->_attachFiles($boundary);
  1541. $msg = array_merge($msg, $attachments);
  1542. }
  1543. if ($hasAttachments || $hasMultipleTypes) {
  1544. $msg[] = '';
  1545. $msg[] = '--' . $boundary . '--';
  1546. $msg[] = '';
  1547. }
  1548. return $msg;
  1549. }
  1550. /**
  1551. * Gets the text body types that are in this email message
  1552. *
  1553. * @return array Array of types. Valid types are 'text' and 'html'
  1554. */
  1555. protected function _getTypes() {
  1556. $types = array($this->_emailFormat);
  1557. if ($this->_emailFormat === 'both') {
  1558. $types = array('html', 'text');
  1559. }
  1560. return $types;
  1561. }
  1562. /**
  1563. * Build and set all the view properties needed to render the templated emails.
  1564. * If there is no template set, the $content will be returned in a hash
  1565. * of the text content types for the email.
  1566. *
  1567. * @param string $content The content passed in from send() in most cases.
  1568. * @return array The rendered content with html and text keys.
  1569. */
  1570. protected function _renderTemplates($content) {
  1571. $types = $this->_getTypes();
  1572. $rendered = array();
  1573. if (empty($this->_template)) {
  1574. foreach ($types as $type) {
  1575. $rendered[$type] = $this->_encodeString($content, $this->charset);
  1576. }
  1577. return $rendered;
  1578. }
  1579. $viewClass = $this->_viewRender;
  1580. if ($viewClass === 'View') {
  1581. $viewClass = App::className('View', 'View');
  1582. } else {
  1583. $viewClass = App::className($viewClass, 'View', 'View');
  1584. }
  1585. $View = new $viewClass(null);
  1586. $View->viewVars = $this->_viewVars;
  1587. $View->helpers = $this->_helpers;
  1588. if ($this->_theme) {
  1589. $View->theme = $this->_theme;
  1590. }
  1591. $View->loadHelpers();
  1592. list($templatePlugin, $template) = pluginSplit($this->_template);
  1593. list($layoutPlugin, $layout) = pluginSplit($this->_layout);
  1594. if ($templatePlugin) {
  1595. $View->plugin = $templatePlugin;
  1596. } elseif ($layoutPlugin) {
  1597. $View->plugin = $layoutPlugin;
  1598. }
  1599. if ($View->get('content') === null) {
  1600. $View->set('content', $content);
  1601. }
  1602. // Convert null to false, as View needs false to disable
  1603. // the layout.
  1604. if ($this->_layout === null) {
  1605. $this->_layout = false;
  1606. }
  1607. foreach ($types as $type) {
  1608. $View->hasRendered = false;
  1609. $View->viewPath = $View->layoutPath = 'Email/' . $type;
  1610. $render = $View->render($this->_template, $this->_layout);
  1611. $render = str_replace(array("\r\n", "\r"), "\n", $render);
  1612. $rendered[$type] = $this->_encodeString($render, $this->charset);
  1613. }
  1614. foreach ($rendered as $type => $content) {
  1615. $rendered[$type] = $this->_wrap($content);
  1616. $rendered[$type] = implode("\n", $rendered[$type]);
  1617. $rendered[$type] = rtrim($rendered[$type], "\n");
  1618. }
  1619. return $rendered;
  1620. }
  1621. /**
  1622. * Return the Content-Transfer Encoding value based on the set charset
  1623. *
  1624. * @return string
  1625. */
  1626. protected function _getContentTransferEncoding() {
  1627. $charset = strtoupper($this->charset);
  1628. if (in_array($charset, $this->_charset8bit)) {
  1629. return '8bit';
  1630. }
  1631. return '7bit';
  1632. }
  1633. /**
  1634. * Return charset value for Content-Type.
  1635. *
  1636. * Checks fallback/compatibility types which include workarounds
  1637. * for legacy japanese character sets.
  1638. *
  1639. * @return string
  1640. */
  1641. protected function _getContentTypeCharset() {
  1642. $charset = strtoupper($this->charset);
  1643. if (array_key_exists($charset, $this->_contentTypeCharset)) {
  1644. return strtoupper($this->_contentTypeCharset[$charset]);
  1645. }
  1646. return strtoupper($this->charset);
  1647. }
  1648. }