EmailLib.php 18 KB

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