PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Network/Email/SmtpTransport.php

https://gitlab.com/shubam39/CakeTooDoo
PHP | 373 lines | 178 code | 34 blank | 161 comment | 26 complexity | f0b292ab5aac6ce4f3b0eebd945d15d7 MD5 | raw file
  1. <?php
  2. /**
  3. * Send mail using SMTP protocol
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Network.Email
  15. * @since CakePHP(tm) v 2.0.0
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('CakeSocket', 'Network');
  19. /**
  20. * Send mail using SMTP protocol
  21. *
  22. * @package Cake.Network.Email
  23. */
  24. class SmtpTransport extends AbstractTransport {
  25. /**
  26. * Socket to SMTP server
  27. *
  28. * @var CakeSocket
  29. */
  30. protected $_socket;
  31. /**
  32. * CakeEmail
  33. *
  34. * @var CakeEmail
  35. */
  36. protected $_cakeEmail;
  37. /**
  38. * Content of email to return
  39. *
  40. * @var string
  41. */
  42. protected $_content;
  43. /**
  44. * The response of the last sent SMTP command.
  45. *
  46. * @var array
  47. */
  48. protected $_lastResponse = array();
  49. /**
  50. * Returns the response of the last sent SMTP command.
  51. *
  52. * A response consists of one or more lines containing a response
  53. * code and an optional response message text:
  54. * {{{
  55. * array(
  56. * array(
  57. * 'code' => '250',
  58. * 'message' => 'mail.example.com'
  59. * ),
  60. * array(
  61. * 'code' => '250',
  62. * 'message' => 'PIPELINING'
  63. * ),
  64. * array(
  65. * 'code' => '250',
  66. * 'message' => '8BITMIME'
  67. * ),
  68. * // etc...
  69. * )
  70. * }}}
  71. *
  72. * @return array
  73. */
  74. public function getLastResponse() {
  75. return $this->_lastResponse;
  76. }
  77. /**
  78. * Send mail
  79. *
  80. * @param CakeEmail $email CakeEmail
  81. * @return array
  82. * @throws SocketException
  83. */
  84. public function send(CakeEmail $email) {
  85. $this->_cakeEmail = $email;
  86. $this->_connect();
  87. $this->_auth();
  88. $this->_sendRcpt();
  89. $this->_sendData();
  90. $this->_disconnect();
  91. return $this->_content;
  92. }
  93. /**
  94. * Set the configuration
  95. *
  96. * @param array $config Configuration options.
  97. * @return array Returns configs
  98. */
  99. public function config($config = null) {
  100. if ($config === null) {
  101. return $this->_config;
  102. }
  103. $default = array(
  104. 'host' => 'localhost',
  105. 'port' => 25,
  106. 'timeout' => 30,
  107. 'username' => null,
  108. 'password' => null,
  109. 'client' => null,
  110. 'tls' => false
  111. );
  112. $this->_config = array_merge($default, $this->_config, $config);
  113. return $this->_config;
  114. }
  115. /**
  116. * Parses and stores the reponse lines in `'code' => 'message'` format.
  117. *
  118. * @param array $responseLines Response lines to parse.
  119. * @return void
  120. */
  121. protected function _bufferResponseLines(array $responseLines) {
  122. $response = array();
  123. foreach ($responseLines as $responseLine) {
  124. if (preg_match('/^(\d{3})(?:[ -]+(.*))?$/', $responseLine, $match)) {
  125. $response[] = array(
  126. 'code' => $match[1],
  127. 'message' => isset($match[2]) ? $match[2] : null
  128. );
  129. }
  130. }
  131. $this->_lastResponse = array_merge($this->_lastResponse, $response);
  132. }
  133. /**
  134. * Connect to SMTP Server
  135. *
  136. * @return void
  137. * @throws SocketException
  138. */
  139. protected function _connect() {
  140. $this->_generateSocket();
  141. if (!$this->_socket->connect()) {
  142. throw new SocketException(__d('cake_dev', 'Unable to connect to SMTP server.'));
  143. }
  144. $this->_smtpSend(null, '220');
  145. if (isset($this->_config['client'])) {
  146. $host = $this->_config['client'];
  147. } elseif ($httpHost = env('HTTP_HOST')) {
  148. list($host) = explode(':', $httpHost);
  149. } else {
  150. $host = 'localhost';
  151. }
  152. try {
  153. $this->_smtpSend("EHLO {$host}", '250');
  154. if ($this->_config['tls']) {
  155. $this->_smtpSend("STARTTLS", '220');
  156. $this->_socket->enableCrypto('tls');
  157. $this->_smtpSend("EHLO {$host}", '250');
  158. }
  159. } catch (SocketException $e) {
  160. if ($this->_config['tls']) {
  161. throw new SocketException(__d('cake_dev', 'SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.'));
  162. }
  163. try {
  164. $this->_smtpSend("HELO {$host}", '250');
  165. } catch (SocketException $e2) {
  166. throw new SocketException(__d('cake_dev', 'SMTP server did not accept the connection.'));
  167. }
  168. }
  169. }
  170. /**
  171. * Send authentication
  172. *
  173. * @return void
  174. * @throws SocketException
  175. */
  176. protected function _auth() {
  177. if (isset($this->_config['username']) && isset($this->_config['password'])) {
  178. $authRequired = $this->_smtpSend('AUTH LOGIN', '334|503');
  179. if ($authRequired == '334') {
  180. if (!$this->_smtpSend(base64_encode($this->_config['username']), '334')) {
  181. throw new SocketException(__d('cake_dev', 'SMTP server did not accept the username.'));
  182. }
  183. if (!$this->_smtpSend(base64_encode($this->_config['password']), '235')) {
  184. throw new SocketException(__d('cake_dev', 'SMTP server did not accept the password.'));
  185. }
  186. } elseif ($authRequired == '504') {
  187. throw new SocketException(__d('cake_dev', 'SMTP authentication method not allowed, check if SMTP server requires TLS'));
  188. } elseif ($authRequired != '503') {
  189. throw new SocketException(__d('cake_dev', 'SMTP does not require authentication.'));
  190. }
  191. }
  192. }
  193. /**
  194. * Prepares the `MAIL FROM` SMTP command.
  195. *
  196. * @param string $email The email address to send with the command.
  197. * @return string
  198. */
  199. protected function _prepareFromCmd($email) {
  200. return 'MAIL FROM:<' . $email . '>';
  201. }
  202. /**
  203. * Prepares the `RCPT TO` SMTP command.
  204. *
  205. * @param string $email The email address to send with the command.
  206. * @return string
  207. */
  208. protected function _prepareRcptCmd($email) {
  209. return 'RCPT TO:<' . $email . '>';
  210. }
  211. /**
  212. * Prepares the `from` email address.
  213. *
  214. * @return array
  215. */
  216. protected function _prepareFromAddress() {
  217. $from = $this->_cakeEmail->returnPath();
  218. if (empty($from)) {
  219. $from = $this->_cakeEmail->from();
  220. }
  221. return $from;
  222. }
  223. /**
  224. * Prepares the recipient email addresses.
  225. *
  226. * @return array
  227. */
  228. protected function _prepareRecipientAddresses() {
  229. $to = $this->_cakeEmail->to();
  230. $cc = $this->_cakeEmail->cc();
  231. $bcc = $this->_cakeEmail->bcc();
  232. return array_merge(array_keys($to), array_keys($cc), array_keys($bcc));
  233. }
  234. /**
  235. * Prepares the message headers.
  236. *
  237. * @return array
  238. */
  239. protected function _prepareMessageHeaders() {
  240. return $this->_cakeEmail->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'to', 'cc', 'subject'));
  241. }
  242. /**
  243. * Prepares the message body.
  244. *
  245. * @return string
  246. */
  247. protected function _prepareMessage() {
  248. $lines = $this->_cakeEmail->message();
  249. $messages = array();
  250. foreach ($lines as $line) {
  251. if ((!empty($line)) && ($line[0] === '.')) {
  252. $messages[] = '.' . $line;
  253. } else {
  254. $messages[] = $line;
  255. }
  256. }
  257. return implode("\r\n", $messages);
  258. }
  259. /**
  260. * Send emails
  261. *
  262. * @return void
  263. * @throws SocketException
  264. */
  265. protected function _sendRcpt() {
  266. $from = $this->_prepareFromAddress();
  267. $this->_smtpSend($this->_prepareFromCmd(key($from)));
  268. $emails = $this->_prepareRecipientAddresses();
  269. foreach ($emails as $email) {
  270. $this->_smtpSend($this->_prepareRcptCmd($email));
  271. }
  272. }
  273. /**
  274. * Send Data
  275. *
  276. * @return void
  277. * @throws SocketException
  278. */
  279. protected function _sendData() {
  280. $this->_smtpSend('DATA', '354');
  281. $headers = $this->_headersToString($this->_prepareMessageHeaders());
  282. $message = $this->_prepareMessage();
  283. $this->_smtpSend($headers . "\r\n\r\n" . $message . "\r\n\r\n\r\n.");
  284. $this->_content = array('headers' => $headers, 'message' => $message);
  285. }
  286. /**
  287. * Disconnect
  288. *
  289. * @return void
  290. * @throws SocketException
  291. */
  292. protected function _disconnect() {
  293. $this->_smtpSend('QUIT', false);
  294. $this->_socket->disconnect();
  295. }
  296. /**
  297. * Helper method to generate socket
  298. *
  299. * @return void
  300. * @throws SocketException
  301. */
  302. protected function _generateSocket() {
  303. $this->_socket = new CakeSocket($this->_config);
  304. }
  305. /**
  306. * Protected method for sending data to SMTP connection
  307. *
  308. * @param string $data data to be sent to SMTP server
  309. * @param string|bool $checkCode code to check for in server response, false to skip
  310. * @return void
  311. * @throws SocketException
  312. */
  313. protected function _smtpSend($data, $checkCode = '250') {
  314. $this->_lastResponse = array();
  315. if ($data !== null) {
  316. $this->_socket->write($data . "\r\n");
  317. }
  318. while ($checkCode !== false) {
  319. $response = '';
  320. $startTime = time();
  321. while (substr($response, -2) !== "\r\n" && ((time() - $startTime) < $this->_config['timeout'])) {
  322. $response .= $this->_socket->read();
  323. }
  324. if (substr($response, -2) !== "\r\n") {
  325. throw new SocketException(__d('cake_dev', 'SMTP timeout.'));
  326. }
  327. $responseLines = explode("\r\n", rtrim($response, "\r\n"));
  328. $response = end($responseLines);
  329. $this->_bufferResponseLines($responseLines);
  330. if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
  331. if ($code[2] === '-') {
  332. continue;
  333. }
  334. return $code[1];
  335. }
  336. throw new SocketException(__d('cake_dev', 'SMTP Error: %s', $response));
  337. }
  338. }
  339. }