EmailLib.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. <?php
  2. App::uses('CakeEmail', 'Network/Email');
  3. App::uses('CakeLog', 'Log');
  4. App::uses('Utility', 'Tools.Utility');
  5. App::uses('MimeLib', 'Tools.Lib');
  6. if (!defined('BR')) {
  7. define('BR', '<br />');
  8. }
  9. // Support BC (snake case config)
  10. if (!Configure::read('Config.systemEmail')) {
  11. Configure::write('Config.systemEmail', Configure::read('Config.system_email'));
  12. }
  13. if (!Configure::read('Config.systemName')) {
  14. Configure::write('Config.systemName', Configure::read('Config.system_name'));
  15. }
  16. if (!Configure::read('Config.adminEmail')) {
  17. Configure::write('Config.adminEmail', Configure::read('Config.admin_email'));
  18. }
  19. if (!Configure::read('Config.adminName')) {
  20. Configure::write('Config.adminName', Configure::read('Config.admin_name'));
  21. }
  22. /**
  23. * Convenience class for internal mailer.
  24. *
  25. * Adds some useful features and fixes some bugs:
  26. * - enable easier attachment adding (and also from blob)
  27. * - enable embedded images in html mails
  28. * - extensive logging and error tracing
  29. * - create mails with blob attachments (embedded or attached)
  30. * - allow wrapLength to be adjusted
  31. * - Configure::read('Config.xMailer') can modify the x-mailer
  32. * - basic validation supported
  33. * - allow priority to be set (1 to 5)
  34. *
  35. * Configs for auto-from can be set via Configure::read('Config.adminEmail').
  36. * For systemEmail() one also needs Configure value Config.systemEmail to be set.
  37. *
  38. * @author Mark Scherer
  39. * @license MIT
  40. * @cakephp 2.x
  41. */
  42. class EmailLib extends CakeEmail {
  43. protected $_log = null;
  44. protected $_debug = null;
  45. protected $_error = null;
  46. protected $_wrapLength = null;
  47. protected $_priority = null;
  48. public function __construct($config = null) {
  49. if ($config === null) {
  50. $config = 'default';
  51. }
  52. parent::__construct($config);
  53. $this->resetAndSet();
  54. }
  55. /**
  56. * Quick way to send emails to admin.
  57. * App::uses() + EmailLib::systemEmail()
  58. *
  59. * Note: always go out with default settings (e.g.: SMTP even if debug > 0)
  60. *
  61. * @param string $subject
  62. * @param string $message
  63. * @param string $transportConfig
  64. * @return bool Success
  65. */
  66. public static function systemEmail($subject, $message = 'System Email', $transportConfig = null) {
  67. $class = __CLASS__;
  68. $instance = new $class($transportConfig);
  69. $instance->from(Configure::read('Config.systemEmail'), Configure::read('Config.systemName'));
  70. $instance->to(Configure::read('Config.adminEmail'), Configure::read('Config.adminName'));
  71. if ($subject !== null) {
  72. $instance->subject($subject);
  73. }
  74. if (is_array($message)) {
  75. $instance->viewVars($message);
  76. $message = null;
  77. } elseif ($message === null && array_key_exists('message', $config = $instance->config())) {
  78. $message = $config['message'];
  79. }
  80. return $instance->send($message);
  81. }
  82. /**
  83. * Change the layout
  84. *
  85. * @param string $layout Layout to use (or false to use none)
  86. * @return resource EmailLib
  87. */
  88. public function layout($layout = false) {
  89. if ($layout !== false) {
  90. $this->_layout = $layout;
  91. }
  92. return $this;
  93. }
  94. /**
  95. * Add an attachment from file
  96. *
  97. * @param string $file: absolute path
  98. * @param string $filename
  99. * @param array $fileInfo
  100. * @return resource EmailLib
  101. */
  102. public function addAttachment($file, $name = null, $fileInfo = array()) {
  103. $fileInfo['file'] = $file;
  104. if (!empty($name)) {
  105. $fileInfo = array($name => $fileInfo);
  106. } else {
  107. $fileInfo = array($fileInfo);
  108. }
  109. return $this->addAttachments($fileInfo);
  110. }
  111. /**
  112. * Add an attachment as blob
  113. *
  114. * @param binary $content: blob data
  115. * @param string $filename to attach it
  116. * @param string $mimeType (leave it empty to get mimetype from $filename)
  117. * @param array $fileInfo
  118. * @return resource EmailLib
  119. */
  120. public function addBlobAttachment($content, $name, $mimeType = null, $fileInfo = array()) {
  121. $fileInfo['content'] = $content;
  122. $fileInfo['mimetype'] = $mimeType;
  123. $file = array($name => $fileInfo);
  124. return $this->addAttachments($file);
  125. }
  126. /**
  127. * Add an inline attachment from file
  128. *
  129. * @param string $file: absolute path
  130. * @param string $filename (optional)
  131. * @param string $contentId (optional)
  132. * @param array $options
  133. * - mimetype
  134. * - contentDisposition
  135. * @return mixed resource $EmailLib or string $contentId
  136. */
  137. public function addEmbeddedAttachment($file, $name = null, $contentId = null, $options = array()) {
  138. if (empty($name)) {
  139. $name = basename($file);
  140. }
  141. if ($contentId === null && ($cid = $this->_isEmbeddedAttachment($file, $name))) {
  142. return $cid;
  143. }
  144. $options['file'] = $file;
  145. if (empty($options['mimetype'])) {
  146. $options['mimetype'] = $this->_getMime($file);
  147. }
  148. $options['contentId'] = $contentId ? $contentId : str_replace('-', '', String::uuid()) . '@' . $this->_domain;
  149. $file = array($name => $options);
  150. $res = $this->addAttachments($file);
  151. if ($contentId === null) {
  152. return $options['contentId'];
  153. }
  154. return $res;
  155. }
  156. /**
  157. * Add an inline attachment as blob
  158. *
  159. * @param binary $content: blob data
  160. * @param string $filename to attach it
  161. * @param string $mimeType (leave it empty to get mimetype from $filename)
  162. * @param string $contentId (optional)
  163. * @param array $options
  164. * - contentDisposition
  165. * @return mixed resource $EmailLib or string $contentId
  166. */
  167. public function addEmbeddedBlobAttachment($content, $name, $mimeType = null, $contentId = null, $options = array()) {
  168. $options['content'] = $content;
  169. $options['mimetype'] = $mimeType;
  170. $options['contentId'] = $contentId ? $contentId : str_replace('-', '', String::uuid()) . '@' . $this->_domain;
  171. $file = array($name => $options);
  172. $res = $this->addAttachments($file);
  173. if ($contentId === null) {
  174. return $options['contentId'];
  175. }
  176. return $res;
  177. }
  178. /**
  179. * Returns if this particular file has already been attached as embedded file with this exact name
  180. * to prevent the same image to overwrite each other and also to only send this image once.
  181. * Allows multiple usage of the same embedded image (using the same cid)
  182. *
  183. * @return string cid of the found file or false if no such attachment can be found
  184. */
  185. protected function _isEmbeddedAttachment($file, $name) {
  186. foreach ($this->_attachments as $filename => $fileInfo) {
  187. if ($filename !== $name) {
  188. continue;
  189. }
  190. if ($fileInfo['file'] === $file) {
  191. return $fileInfo['contentId'];
  192. }
  193. }
  194. return false;
  195. }
  196. /**
  197. * Try to determine the mimetype by filename.
  198. * Uses finfo_open() if availble, otherwise guesses it via file extension.
  199. *
  200. * @param string $filename
  201. * @return string Mimetype
  202. */
  203. protected function _getMime($filename) {
  204. $mimetype = Utility::getMimeType($filename);
  205. if (!$mimetype) {
  206. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  207. $mimetype = $this->_getMimeByExtension($ext);
  208. }
  209. return $mimetype;
  210. }
  211. /**
  212. * Try to find mimetype by file extension
  213. *
  214. * @param string $ext lowercase (jpg, png, pdf, ...)
  215. * @param string $defaultMimeType
  216. * @return string Mimetype (falls back to `application/octet-stream`)
  217. */
  218. protected function _getMimeByExtension($ext, $default = 'application/octet-stream') {
  219. if (!$ext) {
  220. return $default;
  221. }
  222. if (!isset($this->_Mime)) {
  223. $this->_Mime = new MimeLib();
  224. }
  225. $mime = $this->_Mime->getMimeType($ext);
  226. if (!$mime) {
  227. $mime = $default;
  228. }
  229. return $mime;
  230. }
  231. /**
  232. * Read the file contents and return a base64 version of the file contents.
  233. * Overwrite parent to avoid File class and file_exists to false negative existent
  234. * remove images.
  235. * Also fixes file_get_contents (used via File class) to close the connection again
  236. * after getting remote files. So far it would have kept the connection open in HTTP/1.1.
  237. *
  238. * @param string $path The absolute path to the file to read.
  239. * @return string File contents in base64 encoding
  240. */
  241. protected function _readFile($path) {
  242. $context = stream_context_create(
  243. array('http' => array('header' => 'Connection: close')));
  244. $content = file_get_contents($path, 0, $context);
  245. if (!$content) {
  246. trigger_error('No content found for ' . $path);
  247. }
  248. return chunk_split(base64_encode($content));
  249. }
  250. /**
  251. * Validate if the email has the required fields necessary to make send() work.
  252. * Assumes layouting (does not check on content to be present or if view/layout files are missing).
  253. *
  254. * @return bool Success
  255. */
  256. public function validates() {
  257. if (!empty($this->_subject) && !empty($this->_to)) {
  258. return true;
  259. }
  260. return false;
  261. }
  262. /**
  263. * Attach inline/embedded files to the message.
  264. *
  265. * CUSTOM FIX: blob data support
  266. *
  267. * @override
  268. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  269. * @return array An array of lines to add to the message
  270. */
  271. protected function _attachInlineFiles($boundary = null) {
  272. if ($boundary === null) {
  273. $boundary = $this->_boundary;
  274. }
  275. $msg = array();
  276. foreach ($this->_attachments as $filename => $fileInfo) {
  277. if (empty($fileInfo['contentId'])) {
  278. continue;
  279. }
  280. if (!empty($fileInfo['content'])) {
  281. $data = $fileInfo['content'];
  282. $data = chunk_split(base64_encode($data));
  283. } elseif (!empty($fileInfo['file'])) {
  284. $data = $this->_readFile($fileInfo['file']);
  285. } else {
  286. continue;
  287. }
  288. $msg[] = '--' . $boundary;
  289. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  290. $msg[] = 'Content-Transfer-Encoding: base64';
  291. $msg[] = 'Content-ID: <' . $fileInfo['contentId'] . '>';
  292. $msg[] = 'Content-Disposition: inline; filename="' . $filename . '"';
  293. $msg[] = '';
  294. $msg[] = $data;
  295. $msg[] = '';
  296. }
  297. return $msg;
  298. }
  299. /**
  300. * Attach non-embedded files by adding file contents inside boundaries.
  301. *
  302. * CUSTOM FIX: blob data support
  303. *
  304. * @override
  305. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  306. * @return array An array of lines to add to the message
  307. */
  308. protected function _attachFiles($boundary = null) {
  309. if ($boundary === null) {
  310. $boundary = $this->_boundary;
  311. }
  312. $msg = array();
  313. foreach ($this->_attachments as $filename => $fileInfo) {
  314. if (!empty($fileInfo['contentId'])) {
  315. continue;
  316. }
  317. if (!empty($fileInfo['content'])) {
  318. $data = $fileInfo['content'];
  319. $data = chunk_split(base64_encode($data));
  320. } elseif (!empty($fileInfo['file'])) {
  321. $data = $this->_readFile($fileInfo['file']);
  322. } else {
  323. continue;
  324. }
  325. $msg[] = '--' . $boundary;
  326. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  327. $msg[] = 'Content-Transfer-Encoding: base64';
  328. if (
  329. !isset($fileInfo['contentDisposition']) ||
  330. $fileInfo['contentDisposition']
  331. ) {
  332. $msg[] = 'Content-Disposition: attachment; filename="' . $filename . '"';
  333. }
  334. $msg[] = '';
  335. $msg[] = $data;
  336. $msg[] = '';
  337. }
  338. return $msg;
  339. }
  340. /**
  341. * Add attachments to the email message
  342. *
  343. * CUSTOM FIX: Allow URLs
  344. * CUSTOM FIX: Blob data support
  345. *
  346. * Attachments can be defined in a few forms depending on how much control you need:
  347. *
  348. * Attach a single file:
  349. *
  350. * {{{
  351. * $email->attachments('path/to/file');
  352. * }}}
  353. *
  354. * Attach a file with a different filename:
  355. *
  356. * {{{
  357. * $email->attachments(array('custom_name.txt' => 'path/to/file.txt'));
  358. * }}}
  359. *
  360. * Attach a file and specify additional properties:
  361. *
  362. * {{{
  363. * $email->attachments(array('custom_name.png' => array(
  364. * 'file' => 'path/to/file',
  365. * 'mimetype' => 'image/png',
  366. * 'contentId' => 'abc123'
  367. * ));
  368. * }}}
  369. *
  370. * The `contentId` key allows you to specify an inline attachment. In your email text, you
  371. * can use `<img src="cid:abc123" />` to display the image inline.
  372. *
  373. * @override
  374. * @param mixed $attachments String with the filename or array with filenames
  375. * @return mixed Either the array of attachments when getting or $this when setting.
  376. * @throws SocketException
  377. */
  378. public function attachments($attachments = null) {
  379. if ($attachments === null) {
  380. return $this->_attachments;
  381. }
  382. $attach = array();
  383. foreach ((array)$attachments as $name => $fileInfo) {
  384. if (!is_array($fileInfo)) {
  385. $fileInfo = array('file' => $fileInfo);
  386. }
  387. if (empty($fileInfo['content'])) {
  388. if (!isset($fileInfo['file'])) {
  389. throw new SocketException(__d('cake_dev', 'File not specified.'));
  390. }
  391. $fileName = $fileInfo['file'];
  392. if (!preg_match('~^https?://~i', $fileInfo['file'])) {
  393. $fileInfo['file'] = realpath($fileInfo['file']);
  394. }
  395. if ($fileInfo['file'] === false || !Utility::fileExists($fileInfo['file'])) {
  396. throw new SocketException(__d('cake_dev', 'File not found: "%s"', $fileName));
  397. }
  398. if (is_int($name)) {
  399. $name = basename($fileInfo['file']);
  400. }
  401. }
  402. if (empty($fileInfo['mimetype'])) {
  403. $ext = pathinfo($name, PATHINFO_EXTENSION);
  404. $fileInfo['mimetype'] = $this->_getMimeByExtension($ext);
  405. }
  406. $attach[$name] = $fileInfo;
  407. }
  408. $this->_attachments = $attach;
  409. return $this;
  410. }
  411. /**
  412. * Set the body of the mail as we send it.
  413. * Note: the text can be an array, each element will appear as a seperate line in the message body.
  414. *
  415. * Do NOT pass a message if you use $this->set() in combination with templates
  416. *
  417. * @overwrite
  418. * @param string/array: message
  419. * @return bool Success
  420. */
  421. public function send($message = null) {
  422. $this->_log = array(
  423. 'to' => $this->_to,
  424. 'from' => $this->_from,
  425. 'sender' => $this->_sender,
  426. 'replyTo' => $this->_replyTo,
  427. 'cc' => $this->_cc,
  428. 'subject' => $this->_subject,
  429. 'bcc' => $this->_bcc,
  430. 'transport' => $this->_transportName
  431. );
  432. if ($this->_priority) {
  433. $this->_headers['X-Priority'] = $this->_priority;
  434. //$this->_headers['X-MSMail-Priority'] = 'High';
  435. //$this->_headers['Importance'] = 'High';
  436. }
  437. // Security measure to not sent to the actual addressee in debug mode while email sending is live
  438. if (Configure::read('debug') && Configure::read('Email.live')) {
  439. $adminEmail = Configure::read('Config.adminEmail');
  440. if (!$adminEmail) {
  441. $adminEmail = Configure::read('Config.systemEmail');
  442. }
  443. foreach ($this->_to as $k => $v) {
  444. if ($k === $adminEmail) {
  445. continue;
  446. }
  447. unset($this->_to[$k]);
  448. $this->_to[$adminEmail] = $v;
  449. }
  450. foreach ($this->_cc as $k => $v) {
  451. if ($k === $adminEmail) {
  452. continue;
  453. }
  454. unset($this->_cc[$k]);
  455. $this->_cc[$adminEmail] = $v;
  456. }
  457. foreach ($this->_bcc as $k => $v) {
  458. if ($k === $adminEmail) {
  459. continue;
  460. }
  461. unset($this->_bcc[$k]);
  462. $this->_bcc[] = $v;
  463. }
  464. }
  465. try {
  466. $this->_debug = parent::send($message);
  467. } catch (Exception $e) {
  468. $this->_error = $e->getMessage();
  469. $this->_error .= ' (line ' . $e->getLine() . ' in ' . $e->getFile() . ')' . PHP_EOL .
  470. $e->getTraceAsString();
  471. if (!empty($this->_config['logReport'])) {
  472. $this->_logEmail();
  473. } else {
  474. CakeLog::write('error', $this->_error);
  475. }
  476. return false;
  477. }
  478. if (!empty($this->_config['logReport'])) {
  479. $this->_logEmail();
  480. }
  481. return true;
  482. }
  483. /**
  484. * Allow modifications of the message
  485. *
  486. * @param string $text
  487. * @return string Text
  488. */
  489. protected function _prepMessage($text) {
  490. return $text;
  491. }
  492. /**
  493. * Returns the error if existent
  494. *
  495. * @return string
  496. */
  497. public function getError() {
  498. return $this->_error;
  499. }
  500. /**
  501. * Returns the log if existent
  502. *
  503. * @return string
  504. */
  505. public function getLog() {
  506. return $this->_log;
  507. }
  508. /**
  509. * Returns the debug content returned by send()
  510. *
  511. * @return string
  512. */
  513. public function getDebug() {
  514. return $this->_debug;
  515. }
  516. /**
  517. * Set/Get wrapLength
  518. *
  519. * @param int $length Must not be more than CakeEmail::LINE_LENGTH_MUST
  520. * @return int|CakeEmail
  521. */
  522. public function wrapLength($length = null) {
  523. if ($length === null) {
  524. return $this->_wrapLength;
  525. }
  526. $this->_wrapLength = $length;
  527. return $this;
  528. }
  529. /**
  530. * Set/Get priority
  531. *
  532. * @param int $priority 1 (highest) to 5 (lowest)
  533. * @return int|CakeEmail
  534. */
  535. public function priority($priority = null) {
  536. if ($priority === null) {
  537. return $this->_priority;
  538. }
  539. $this->_priority = $priority;
  540. return $this;
  541. }
  542. /**
  543. * Fix line length
  544. *
  545. * @overwrite
  546. * @param string $message Message to wrap
  547. * @return array Wrapped message
  548. */
  549. protected function _wrap($message, $wrapLength = CakeEmail::LINE_LENGTH_MUST) {
  550. if ($this->_wrapLength !== null) {
  551. $wrapLength = $this->_wrapLength;
  552. }
  553. return parent::_wrap($message, $wrapLength);
  554. }
  555. /**
  556. * Logs Email to type email
  557. *
  558. * @return void
  559. */
  560. protected function _logEmail($append = null) {
  561. $res = $this->_log['transport'] .
  562. ' - ' . 'TO:' . implode(',', array_keys($this->_log['to'])) .
  563. '||FROM:' . implode(',', array_keys($this->_log['from'])) .
  564. '||REPLY:' . implode(',', array_keys($this->_log['replyTo'])) .
  565. '||S:' . $this->_log['subject'];
  566. $type = 'email';
  567. if (!empty($this->_error)) {
  568. $type = 'email_error';
  569. $res .= '||ERROR:' . $this->_error;
  570. }
  571. if ($append) {
  572. $res .= '||' . $append;
  573. }
  574. CakeLog::write($type, $res);
  575. }
  576. /**
  577. * EmailLib::resetAndSet()
  578. *
  579. * @return void
  580. */
  581. public function resetAndSet() {
  582. $this->_to = array();
  583. $this->_cc = array();
  584. $this->_bcc = array();
  585. $this->_messageId = true;
  586. $this->_subject = '';
  587. $this->_headers = array();
  588. $this->_viewVars = array();
  589. $this->_textMessage = '';
  590. $this->_htmlMessage = '';
  591. $this->_message = '';
  592. $this->_attachments = array();
  593. $this->_error = null;
  594. $this->_debug = null;
  595. if ($fromEmail = Configure::read('Config.systemEmail')) {
  596. $fromName = Configure::read('Config.systemName');
  597. } else {
  598. $fromEmail = Configure::read('Config.adminEmail');
  599. $fromName = Configure::read('Config.adminName');
  600. }
  601. if (!$fromEmail) {
  602. throw new RuntimeException('You need to either define systemEmail or adminEmail in Config.');
  603. }
  604. $this->from($fromEmail, $fromName);
  605. if ($xMailer = Configure::read('Config.xMailer')) {
  606. $this->addHeaders(array('X-Mailer' => $xMailer));
  607. }
  608. }
  609. }