EmailLib.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. <?php
  2. App::uses('CakeEmail', 'Network/Email');
  3. App::uses('CakeLog', 'Log');
  4. if (!defined('BR')) {
  5. define('BR', '<br />');
  6. }
  7. /**
  8. * Convenience class for internal mailer.
  9. * Adds some nice features and fixes some bugs:
  10. * - enbale embedded images in html mails
  11. * - allow setting domain for CLI environment (now in core)
  12. * - enable easier attachment adding
  13. * - extensive logging and error tracing
  14. * - create mails with blob attachments (embedded or attached)
  15. * TODO: cleanup and more tests
  16. *
  17. * @author Mark Scherer
  18. * @license MIT
  19. * @cakephp 2.2
  20. * 2012-03-30 ms
  21. */
  22. class EmailLib extends CakeEmail {
  23. protected $_log = null;
  24. protected $_debug = null;
  25. public $error = '';
  26. # for multiple emails, just adjust these "default" values "on the fly"
  27. public $deliveryMethod = 'mail';
  28. public $layout = 'external'; # usually 'external' (internal for admins only)
  29. # with presets, only TO/FROM (depends), subject and message has to be set
  30. public $presets = array(
  31. 'user' => '',
  32. 'admin' => '',
  33. );
  34. public $options = array();
  35. public $complex = null; # if Controller is available, and layout/elements can be switched...
  36. public function __construct($config = null) {
  37. if ($config === null) {
  38. $config = 'default';
  39. }
  40. parent::__construct($config);
  41. $this->resetAndSet();
  42. }
  43. /**
  44. * quick way to send emails to admin
  45. * App::uses() + EmailLib::systemEmail()
  46. *
  47. * Note: always go out with default settings (e.g.: SMTP even if debug > 0)
  48. * @return bool $success
  49. * 2011-10-31 ms
  50. */
  51. public static function systemEmail($subject, $message = 'System Email', $transportConfig = null) {
  52. $class = __CLASS__;
  53. $instance = new $class($transportConfig);
  54. $instance->to(Configure::read('Config.admin_email'));
  55. $instance->from(Configure::read('Config.admin_email'));
  56. if ($subject !== null) {
  57. $instance->subject($subject);
  58. }
  59. if (is_array($message)) {
  60. $instance->viewVars($message);
  61. $message = null;
  62. } elseif ($message === null && array_key_exists('message', $config = $instance->config())) {
  63. $message = $config['message'];
  64. }
  65. if (true || $send === true) {
  66. return $instance->send($message);
  67. }
  68. return $instance;
  69. }
  70. public function layout($layout = false) {
  71. if ($layout !== false) {
  72. $this->_layout = $layout;
  73. }
  74. return $this;
  75. }
  76. /**
  77. * @param string $file: absolute path
  78. * @param string $filename (optional)
  79. * 2011-11-02 ms
  80. */
  81. public function addAttachment($file, $name = null) {
  82. if (!empty($name)) {
  83. return $this->addAttachments(array($name=>$file));
  84. }
  85. return $this->addAttachments($file);
  86. }
  87. /**
  88. * @param binary $content: blob data
  89. * @param string $filename to attach it
  90. * @param string $mimeType (leave it empty to get mimetype from $filename)
  91. * @param string $contentId (optional)
  92. * @return mixed ressource $EmailLib or string $contentId
  93. * 2011-11-02 ms
  94. */
  95. public function addBlobAttachment($content, $name, $mimeType = null) {
  96. $fileInfo = array();
  97. $fileInfo['content'] = $content;
  98. $fileInfo['mimetype'] = $mimeType;
  99. $file = array($name=>$fileInfo);
  100. $res = $this->addAttachments($file);
  101. if ($contentId === null) {
  102. return $fileInfo['contentId'];
  103. }
  104. return $res;
  105. }
  106. /**
  107. * @param binary $content: blob data
  108. * @param string $filename to attach it
  109. * @param string $mimeType (leave it empty to get mimetype from $filename)
  110. * @param string $contentId (optional)
  111. * @return mixed ressource $EmailLib or string $contentId
  112. * 2011-11-02 ms
  113. */
  114. public function addEmbeddedBlobAttachment($content, $name, $mimeType = null, $contentId = null) {
  115. $fileInfo = array();
  116. $fileInfo['content'] = $content;
  117. $fileInfo['mimetype'] = $mimeType;
  118. $fileInfo['contentId'] = $contentId ? $contentId : str_replace('-', '', String::uuid()) . '@' . $this->_domain;
  119. $file = array($name=>$fileInfo);
  120. $res = $this->addAttachments($file);
  121. if ($contentId === null) {
  122. return $fileInfo['contentId'];
  123. }
  124. return $res;
  125. }
  126. /**
  127. * @param string $file: absolute path
  128. * @param string $filename (optional)
  129. * @param string $contentId (optional)
  130. * @return mixed ressource $EmailLib or string $contentId
  131. * 2011-11-02 ms
  132. */
  133. public function addEmbeddedAttachment($file, $name = null, $contentId = null) {
  134. $fileInfo = array();
  135. $fileInfo['file'] = realpath($file);
  136. $fileInfo['mimetype'] = $this->_getMime($file);
  137. $fileInfo['contentId'] = $contentId ? $contentId : str_replace('-', '', String::uuid()) . '@' . $this->_domain;
  138. if (empty($name)) {
  139. $name = basename($file);
  140. }
  141. $file = array($name=>$fileInfo);
  142. $res = $this->addAttachments($file);
  143. if ($contentId === null) {
  144. return $fileInfo['contentId'];
  145. }
  146. return $res;
  147. }
  148. protected function _getMime($filename) {
  149. if (function_exists('finfo_open')) {
  150. $finfo = finfo_open(FILEINFO_MIME);
  151. $mimetype = finfo_file($finfo, $filename);
  152. finfo_close($finfo);
  153. } else {
  154. //TODO: improve
  155. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  156. $mimetype = $this->_getMimeByExtension($ext);
  157. }
  158. return $mimetype;
  159. }
  160. /**
  161. * try to find mimetype by file extension
  162. * @param string $ext lowercase (jpg, png, pdf, ...)
  163. * @param string $defaultMimeType
  164. * @return string $mimeType (falls back to )
  165. * 2012-04-17 ms
  166. */
  167. protected function _getMimeByExtension($ext, $default = 'application/octet-stream') {
  168. switch ($ext) {
  169. case "zip": $mime="application/zip"; break;
  170. case "ez": $mime="application/andrew-inset"; break;
  171. case "hqx": $mime="application/mac-binhex40"; break;
  172. case "cpt": $mime="application/mac-compactpro"; break;
  173. case "doc": $mime="application/msword"; break;
  174. case "bin": $mime="application/octet-stream"; break;
  175. case "dms": $mime="application/octet-stream"; break;
  176. case "lha": $mime="application/octet-stream"; break;
  177. case "lzh": $mime="application/octet-stream"; break;
  178. case "exe": $mime="application/octet-stream"; break;
  179. case "class": $mime="application/octet-stream"; break;
  180. case "so": $mime="application/octet-stream"; break;
  181. case "dll": $mime="application/octet-stream"; break;
  182. case "oda": $mime="application/oda"; break;
  183. case "pdf": $mime="application/pdf"; break;
  184. case "ai": $mime="application/postscript"; break;
  185. case "eps": $mime="application/postscript"; break;
  186. case "ps": $mime="application/postscript"; break;
  187. case "smi": $mime="application/smil"; break;
  188. case "smil": $mime="application/smil"; break;
  189. case "xls": $mime="application/vnd.ms-excel"; break;
  190. case "ppt": $mime="application/vnd.ms-powerpoint"; break;
  191. case "wbxml": $mime="application/vnd.wap.wbxml"; break;
  192. case "wmlc": $mime="application/vnd.wap.wmlc"; break;
  193. case "wmlsc": $mime="application/vnd.wap.wmlscriptc"; break;
  194. case "bcpio": $mime="application/x-bcpio"; break;
  195. case "vcd": $mime="application/x-cdlink"; break;
  196. case "pgn": $mime="application/x-chess-pgn"; break;
  197. case "cpio": $mime="application/x-cpio"; break;
  198. case "csh": $mime="application/x-csh"; break;
  199. case "dcr": $mime="application/x-director"; break;
  200. case "dir": $mime="application/x-director"; break;
  201. case "dxr": $mime="application/x-director"; break;
  202. case "dvi": $mime="application/x-dvi"; break;
  203. case "spl": $mime="application/x-futuresplash"; break;
  204. case "gtar": $mime="application/x-gtar"; break;
  205. case "hdf": $mime="application/x-hdf"; break;
  206. case "js": $mime="application/x-javascript"; break;
  207. case "skp": $mime="application/x-koan"; break;
  208. case "skd": $mime="application/x-koan"; break;
  209. case "skt": $mime="application/x-koan"; break;
  210. case "skm": $mime="application/x-koan"; break;
  211. case "latex": $mime="application/x-latex"; break;
  212. case "nc": $mime="application/x-netcdf"; break;
  213. case "cdf": $mime="application/x-netcdf"; break;
  214. case "sh": $mime="application/x-sh"; break;
  215. case "shar": $mime="application/x-shar"; break;
  216. case "swf": $mime="application/x-shockwave-flash"; break;
  217. case "sit": $mime="application/x-stuffit"; break;
  218. case "sv4cpio": $mime="application/x-sv4cpio"; break;
  219. case "sv4crc": $mime="application/x-sv4crc"; break;
  220. case "tar": $mime="application/x-tar"; break;
  221. case "tcl": $mime="application/x-tcl"; break;
  222. case "tex": $mime="application/x-tex"; break;
  223. case "texinfo": $mime="application/x-texinfo"; break;
  224. case "texi": $mime="application/x-texinfo"; break;
  225. case "t": $mime="application/x-troff"; break;
  226. case "tr": $mime="application/x-troff"; break;
  227. case "roff": $mime="application/x-troff"; break;
  228. case "man": $mime="application/x-troff-man"; break;
  229. case "me": $mime="application/x-troff-me"; break;
  230. case "ms": $mime="application/x-troff-ms"; break;
  231. case "ustar": $mime="application/x-ustar"; break;
  232. case "src": $mime="application/x-wais-source"; break;
  233. case "xhtml": $mime="application/xhtml+xml"; break;
  234. case "xht": $mime="application/xhtml+xml"; break;
  235. case "zip": $mime="application/zip"; break;
  236. case "au": $mime="audio/basic"; break;
  237. case "snd": $mime="audio/basic"; break;
  238. case "mid": $mime="audio/midi"; break;
  239. case "midi": $mime="audio/midi"; break;
  240. case "kar": $mime="audio/midi"; break;
  241. case "mpga": $mime="audio/mpeg"; break;
  242. case "mp2": $mime="audio/mpeg"; break;
  243. case "mp3": $mime="audio/mpeg"; break;
  244. case "aif": $mime="audio/x-aiff"; break;
  245. case "aiff": $mime="audio/x-aiff"; break;
  246. case "aifc": $mime="audio/x-aiff"; break;
  247. case "m3u": $mime="audio/x-mpegurl"; break;
  248. case "ram": $mime="audio/x-pn-realaudio"; break;
  249. case "rm": $mime="audio/x-pn-realaudio"; break;
  250. case "rpm": $mime="audio/x-pn-realaudio-plugin"; break;
  251. case "ra": $mime="audio/x-realaudio"; break;
  252. case "wav": $mime="audio/x-wav"; break;
  253. case "pdb": $mime="chemical/x-pdb"; break;
  254. case "xyz": $mime="chemical/x-xyz"; break;
  255. case "bmp": $mime="image/bmp"; break;
  256. case "gif": $mime="image/gif"; break;
  257. case "ief": $mime="image/ief"; break;
  258. case "jpeg": $mime="image/jpeg"; break;
  259. case "jpg": $mime="image/jpeg"; break;
  260. case "jpe": $mime="image/jpeg"; break;
  261. case "png": $mime="image/png"; break;
  262. case "tiff": $mime="image/tiff"; break;
  263. case "tif": $mime="image/tiff"; break;
  264. case "djvu": $mime="image/vnd.djvu"; break;
  265. case "djv": $mime="image/vnd.djvu"; break;
  266. case "wbmp": $mime="image/vnd.wap.wbmp"; break;
  267. case "ras": $mime="image/x-cmu-raster"; break;
  268. case "pnm": $mime="image/x-portable-anymap"; break;
  269. case "pbm": $mime="image/x-portable-bitmap"; break;
  270. case "pgm": $mime="image/x-portable-graymap"; break;
  271. case "ppm": $mime="image/x-portable-pixmap"; break;
  272. case "rgb": $mime="image/x-rgb"; break;
  273. case "xbm": $mime="image/x-xbitmap"; break;
  274. case "xpm": $mime="image/x-xpixmap"; break;
  275. case "xwd": $mime="image/x-xwindowdump"; break;
  276. case "igs": $mime="model/iges"; break;
  277. case "iges": $mime="model/iges"; break;
  278. case "msh": $mime="model/mesh"; break;
  279. case "mesh": $mime="model/mesh"; break;
  280. case "silo": $mime="model/mesh"; break;
  281. case "wrl": $mime="model/vrml"; break;
  282. case "vrml": $mime="model/vrml"; break;
  283. case "css": $mime="text/css"; break;
  284. case "html": $mime="text/html"; break;
  285. case "htm": $mime="text/html"; break;
  286. case "asc": $mime="text/plain"; break;
  287. case "txt": $mime="text/plain"; break;
  288. case "rtx": $mime="text/richtext"; break;
  289. case "rtf": $mime="text/rtf"; break;
  290. case "sgml": $mime="text/sgml"; break;
  291. case "sgm": $mime="text/sgml"; break;
  292. case "tsv": $mime="text/tab-separated-values"; break;
  293. case "wml": $mime="text/vnd.wap.wml"; break;
  294. case "wmls": $mime="text/vnd.wap.wmlscript"; break;
  295. case "etx": $mime="text/x-setext"; break;
  296. case "xml": $mime="text/xml"; break;
  297. case "xsl": $mime="text/xml"; break;
  298. case "mpeg": $mime="video/mpeg"; break;
  299. case "mpg": $mime="video/mpeg"; break;
  300. case "mpe": $mime="video/mpeg"; break;
  301. case "qt": $mime="video/quicktime"; break;
  302. case "mov": $mime="video/quicktime"; break;
  303. case "mxu": $mime="video/vnd.mpegurl"; break;
  304. case "avi": $mime="video/x-msvideo"; break;
  305. case "movie": $mime="video/x-sgi-movie"; break;
  306. case "asf": $mime="video/x-ms-asf"; break;
  307. case "asx": $mime="video/x-ms-asf"; break;
  308. case "wm": $mime="video/x-ms-wm"; break;
  309. case "wmv": $mime="video/x-ms-wmv"; break;
  310. case "wvx": $mime="video/x-ms-wvx"; break;
  311. case "ice": $mime="x-conference/x-cooltalk"; break;
  312. }
  313. if (empty($mime)) {
  314. $mime = $default;
  315. }
  316. return $mime;
  317. }
  318. public function preset($type = null) {
  319. # testing only:
  320. //pr ($this->Email);
  321. //pr ($this);
  322. }
  323. /**
  324. * test for a specific error
  325. * @param code: 4xx, 5xx, 5xx 5.1.1, 5xx 5.2.2, ...
  326. * @return boolean $status (TRUE only if this specific error occured)
  327. * 2010-06-08 ms
  328. */
  329. public function hasError($code) {
  330. if (!empty($this->errors)) {
  331. foreach ($this->errors as $error) {
  332. if (substr($error, 0, strlen($code)) == (string)$code) {
  333. return true;
  334. }
  335. }
  336. }
  337. return false;
  338. }
  339. public function validates() {
  340. if (!empty($this->Email->subject)) {
  341. return true;
  342. }
  343. return false;
  344. }
  345. /**
  346. * Domain as top level (the part after @)
  347. *
  348. * @param string $domain Manually set the domain for CLI mailing
  349. * @return mixed
  350. * @throws SocketException
  351. */
  352. public function domain($domain = null) {
  353. $this->_domain = $domain;
  354. return $this;
  355. }
  356. /**
  357. * Attach inline/embedded files to the message.
  358. * @override
  359. * CUSTOM FIX: blob data support
  360. *
  361. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  362. * @return array An array of lines to add to the message
  363. */
  364. protected function _attachInlineFiles($boundary = null) {
  365. if ($boundary === null) {
  366. $boundary = $this->_boundary;
  367. }
  368. $msg = array();
  369. foreach ($this->_attachments as $filename => $fileInfo) {
  370. if (empty($fileInfo['contentId'])) {
  371. continue;
  372. }
  373. if (!empty($fileInfo['content'])) {
  374. $data = $fileInfo['content'];
  375. $data = chunk_split(base64_encode($data));
  376. } elseif (!empty($fileInfo['file'])) {
  377. $data = $this->_readFile($fileInfo['file']);
  378. } else {
  379. continue;
  380. }
  381. $msg[] = '--' . $boundary;
  382. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  383. $msg[] = 'Content-Transfer-Encoding: base64';
  384. $msg[] = 'Content-ID: <' . $fileInfo['contentId'] . '>';
  385. $msg[] = 'Content-Disposition: inline; filename="' . $filename . '"';
  386. $msg[] = '';
  387. $msg[] = $data;
  388. $msg[] = '';
  389. }
  390. return $msg;
  391. }
  392. /**
  393. * Attach non-embedded files by adding file contents inside boundaries.
  394. * @override
  395. * CUSTOM FIX: blob data support
  396. *
  397. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  398. * @return array An array of lines to add to the message
  399. */
  400. protected function _attachFiles($boundary = null) {
  401. if ($boundary === null) {
  402. $boundary = $this->_boundary;
  403. }
  404. $msg = array();
  405. foreach ($this->_attachments as $filename => $fileInfo) {
  406. if (!empty($fileInfo['contentId'])) {
  407. continue;
  408. }
  409. if (!empty($fileInfo['content'])) {
  410. $data = $fileInfo['content'];
  411. $data = chunk_split(base64_encode($data));
  412. } elseif (!empty($fileInfo['file'])) {
  413. $data = $this->_readFile($fileInfo['file']);
  414. } else {
  415. continue;
  416. }
  417. $msg[] = '--' . $boundary;
  418. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  419. $msg[] = 'Content-Transfer-Encoding: base64';
  420. $msg[] = 'Content-Disposition: attachment; filename="' . $filename . '"';
  421. $msg[] = '';
  422. $msg[] = $data;
  423. $msg[] = '';
  424. }
  425. return $msg;
  426. }
  427. /**
  428. * Add attachments to the email message
  429. * @override
  430. * CUSTOM FIX: blob data support
  431. *
  432. * Attachments can be defined in a few forms depending on how much control you need:
  433. *
  434. * Attach a single file:
  435. *
  436. * {{{
  437. * $email->attachments('path/to/file');
  438. * }}}
  439. *
  440. * Attach a file with a different filename:
  441. *
  442. * {{{
  443. * $email->attachments(array('custom_name.txt' => 'path/to/file.txt'));
  444. * }}}
  445. *
  446. * Attach a file and specify additional properties:
  447. *
  448. * {{{
  449. * $email->attachments(array('custom_name.png' => array(
  450. * 'file' => 'path/to/file',
  451. * 'mimetype' => 'image/png',
  452. * 'contentId' => 'abc123'
  453. * ));
  454. * }}}
  455. *
  456. * The `contentId` key allows you to specify an inline attachment. In your email text, you
  457. * can use `<img src="cid:abc123" />` to display the image inline.
  458. *
  459. * @param mixed $attachments String with the filename or array with filenames
  460. * @return mixed Either the array of attachments when getting or $this when setting.
  461. * @throws SocketException
  462. */
  463. public function attachments($attachments = null) {
  464. if ($attachments === null) {
  465. return $this->_attachments;
  466. }
  467. $attach = array();
  468. foreach ((array)$attachments as $name => $fileInfo) {
  469. if (!is_array($fileInfo)) {
  470. $fileInfo = array('file' => $fileInfo);
  471. }
  472. if (empty($fileInfo['content'])) {
  473. if (!isset($fileInfo['file'])) {
  474. throw new SocketException(__d('cake_dev', 'File not specified.'));
  475. }
  476. $fileInfo['file'] = realpath($fileInfo['file']);
  477. if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) {
  478. throw new SocketException(__d('cake_dev', 'File not found: "%s"', $fileInfo['file']));
  479. }
  480. if (is_int($name)) {
  481. $name = basename($fileInfo['file']);
  482. }
  483. }
  484. if (empty($fileInfo['mimetype'])) {
  485. $ext = pathinfo($name, PATHINFO_EXTENSION);
  486. $fileInfo['mimetype'] = $this->_getMimeByExtension($ext);
  487. //$fileInfo['mimetype'] = $this->_getMime($fileInfo['file']);
  488. }
  489. $attach[$name] = $fileInfo;
  490. }
  491. $this->_attachments = $attach;
  492. return $this;
  493. }
  494. /**
  495. * Get list of headers
  496. * @override
  497. * CUSTOM FIX: message id correctly set in CLI and can be passed in via domain()
  498. *
  499. * ### Includes:
  500. *
  501. * - `from`
  502. * - `replyTo`
  503. * - `readReceipt`
  504. * - `returnPath`
  505. * - `to`
  506. * - `cc`
  507. * - `bcc`
  508. * - `subject`
  509. *
  510. * @param array $include
  511. * @return array
  512. */
  513. public function getHeaders($include = array()) {
  514. if ($include == array_values($include)) {
  515. $include = array_fill_keys($include, true);
  516. }
  517. $defaults = array_fill_keys(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'), false);
  518. $include += $defaults;
  519. $headers = array();
  520. $relation = array(
  521. 'from' => 'From',
  522. 'replyTo' => 'Reply-To',
  523. 'readReceipt' => 'Disposition-Notification-To',
  524. 'returnPath' => 'Return-Path'
  525. );
  526. foreach ($relation as $var => $header) {
  527. if ($include[$var]) {
  528. $var = '_' . $var;
  529. $headers[$header] = current($this->_formatAddress($this->{$var}));
  530. }
  531. }
  532. if ($include['sender']) {
  533. if (key($this->_sender) === key($this->_from)) {
  534. $headers['Sender'] = '';
  535. } else {
  536. $headers['Sender'] = current($this->_formatAddress($this->_sender));
  537. }
  538. }
  539. foreach (array('to', 'cc', 'bcc') as $var) {
  540. if ($include[$var]) {
  541. $classVar = '_' . $var;
  542. $headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar}));
  543. }
  544. }
  545. $headers += $this->_headers;
  546. if (!isset($headers['X-Mailer'])) {
  547. $headers['X-Mailer'] = self::EMAIL_CLIENT;
  548. }
  549. if (!isset($headers['Date'])) {
  550. $headers['Date'] = date(DATE_RFC2822);
  551. }
  552. if ($this->_messageId !== false) {
  553. if ($this->_messageId === true) {
  554. $headers['Message-ID'] = '<' . str_replace('-', '', String::UUID()) . '@' . $this->_domain . '>';
  555. } else {
  556. $headers['Message-ID'] = $this->_messageId;
  557. }
  558. }
  559. if ($include['subject']) {
  560. $headers['Subject'] = $this->_subject;
  561. }
  562. $headers['MIME-Version'] = '1.0';
  563. if (!empty($this->_attachments) || $this->_emailFormat === 'both') {
  564. $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"';
  565. } elseif ($this->_emailFormat === 'text') {
  566. $headers['Content-Type'] = 'text/plain; charset=' . $this->charset;
  567. } elseif ($this->_emailFormat === 'html') {
  568. $headers['Content-Type'] = 'text/html; charset=' . $this->charset;
  569. }
  570. $headers['Content-Transfer-Encoding'] = $this->_getContentTransferEncoding();
  571. return $headers;
  572. }
  573. /**
  574. * Apply the config to an instance
  575. *
  576. * @param CakeEmail $obj CakeEmail
  577. * @param array $config
  578. * @return void
  579. * @throws ConfigureException When configuration file cannot be found, or is missing
  580. * the named config.
  581. */
  582. protected function _applyConfig($config) {
  583. if (is_string($config)) {
  584. if (!class_exists('EmailConfig') && !config('email')) {
  585. throw new ConfigureException(__d('cake_dev', '%s not found.', APP . 'Config' . DS . 'email.php'));
  586. }
  587. $configs = new EmailConfig();
  588. if (!isset($configs->{$config})) {
  589. throw new ConfigureException(__d('cake_dev', 'Unknown email configuration "%s".', $config));
  590. }
  591. $config = $configs->{$config};
  592. }
  593. $this->_config += $config;
  594. if (!empty($config['charset'])) {
  595. $this->charset = $config['charset'];
  596. }
  597. if (!empty($config['headerCharset'])) {
  598. $this->headerCharset = $config['headerCharset'];
  599. }
  600. if (empty($this->headerCharset)) {
  601. $this->headerCharset = $this->charset;
  602. }
  603. $simpleMethods = array(
  604. 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', 'cc', 'bcc',
  605. 'messageId', 'domain', 'subject', 'viewRender', 'viewVars', 'attachments',
  606. 'transport', 'emailFormat'
  607. );
  608. foreach ($simpleMethods as $method) {
  609. if (isset($config[$method])) {
  610. $this->$method($config[$method]);
  611. unset($config[$method]);
  612. }
  613. }
  614. if (isset($config['headers'])) {
  615. $this->setHeaders($config['headers']);
  616. unset($config['headers']);
  617. }
  618. if (array_key_exists('template', $config)) {
  619. $layout = false;
  620. if (array_key_exists('layout', $config)) {
  621. $layout = $config['layout'];
  622. unset($config['layout']);
  623. }
  624. $this->template($config['template'], $layout);
  625. unset($config['template']);
  626. }
  627. $this->transportClass()->config($config);
  628. }
  629. /**
  630. * Set the body of the mail as we send it.
  631. * Note: the text can be an array, each element will appear as a seperate line in the message body.
  632. * @param string/array: message
  633. * LEAVE empty if you use $this->set() in combination with templates
  634. */
  635. public function send($message = null) {
  636. $this->_log = array(
  637. 'to' => $this->_to,
  638. 'from' => $this->_from,
  639. 'sender' => $this->_sender,
  640. 'replyTo' => $this->_replyTo,
  641. 'cc' => $this->_cc,
  642. 'subject' => $this->_subject,
  643. 'cc' => $this->_cc,
  644. 'transport' => $this->_transportName
  645. );
  646. # prep images for inline
  647. /*
  648. if ($this->_emailFormat !== 'text') {
  649. if ($message !== null) {
  650. $message = $this->_prepMessage($message);
  651. } else {
  652. $this->_htmlMessage = $this->_prepMessage($this->_htmlMessage);
  653. }
  654. }
  655. */
  656. try {
  657. $this->_debug = parent::send($message);
  658. } catch (Exception $e) {
  659. $this->error = $e->getMessage();
  660. $this->error .= ' (line '.$e->getLine().' in '.$e->getFile().')'.PHP_EOL.$e->getTraceAsString();
  661. if (!empty($this->_config['report'])) {
  662. $this->_logEmail();
  663. }
  664. return false;
  665. }
  666. if (!empty($this->_config['report'])) {
  667. $this->_logEmail();
  668. }
  669. return true;
  670. }
  671. protected function _prepMessage($text) {
  672. return $text;
  673. }
  674. /**
  675. * @return string
  676. */
  677. public function getError() {
  678. return $this->error;
  679. }
  680. protected function _logEmail($append = null) {
  681. $res = $this->_log['transport'].
  682. ' - '.'TO:'.implode(',', array_keys($this->_log['to'])).
  683. '||FROM:'.implode(',', array_keys($this->_log['from'])).
  684. '||REPLY:'.implode(',', array_keys($this->_log['replyTo'])).
  685. '||S:'.$this->_log['subject'];
  686. $type = 'email';
  687. if (!empty($this->error)) {
  688. $type = 'email_error';
  689. $res .= '||ERROR:' . $this->error;
  690. }
  691. if ($append) {
  692. $res .= '||'.$append;
  693. }
  694. CakeLog::write($type, $res);
  695. }
  696. /**
  697. * toggle debug mode
  698. * 2011-05-27 ms
  699. */
  700. public function debug($mode = null) {
  701. if ($mode) {
  702. $this->debug = true;
  703. //$this->delivery('debug');
  704. } else {
  705. $this->debug = false;
  706. //$this->delivery($this->deliveryMethod);
  707. }
  708. }
  709. public function resetAndSet() {
  710. $this->_to = array();
  711. $this->_cc = array();
  712. $this->_bcc = array();
  713. $this->_messageId = true;
  714. $this->_subject = '';
  715. $this->_headers = array();
  716. $this->_viewVars = array();
  717. $this->_textMessage = '';
  718. $this->_htmlMessage = '';
  719. $this->_message = '';
  720. $this->_attachments = array();
  721. $this->from(Configure::read('Config.admin_email'), Configure::read('Config.admin_emailname'));
  722. if ($xMailer = Configure::read('Config.x-mailer')) {
  723. $this->addHeaders(array('X-Mailer'=>$xMailer));
  724. }
  725. //$this->errors = array();
  726. //$this->charset($this->charset);
  727. //$this->sendAs($this->sendAs);
  728. //$this->layout($this->layout);
  729. //$this->delivery($this->deliveryMethod);
  730. }
  731. public function reset() {
  732. parent::reset();
  733. $this->error = '';
  734. $this->_debug = null;
  735. }
  736. public function flashDebug() {
  737. $info = $this->Email->Controller->Session->read('Message.email.message');
  738. if (empty($info)) {
  739. $info = $this->Email->Controller->Session->read('Message.email.message');
  740. }
  741. $info .= BR;
  742. $info .= h($this->_logMessage());
  743. $this->Email->Controller->Session->delete('Message.email');
  744. $this->Email->Controller->flashMessage($info, 'info');
  745. if (!empty($this->errors)) {
  746. $this->Email->Controller->flashMessage(implode(BR, $this->errors), 'error');
  747. }
  748. }
  749. }