Email.php 44 KB

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